The Scala List is an immutable sequence of elements, implemented as a linked list. Unlike an array, a linked list consists of many small objects, each containing a reference to an object as well as a reference to the rest of the list. Lists support efficient addition of new elements at the front.
If you already have the elements, you can create a list using the List keyword:
scala> val a = List(13, 17, 99, 54) a: List[Int] = List(13, 17, 99, 54) scala> val b = List("CS109", "really", "is", "fun") b: List[java.lang.String] = List(CS109, really, is, fun)Otherwise you create an empty list and add elements later:
scala> var l = List[String]() l: List[String] = List()The empty list is equal to Nil:
scala> l == Nil res0: Boolean = true
You can also create new lists using the cons-operator, written :: in Scala:
scala> val t = 37 :: 99 :: 80 :: 34 :: Nil t: List[Int] = List(37, 99, 80, 34)The cons-operator takes an element and a list, and returns a new list with the element prepended at the front. (Its function is identical to the +: operator available for all Scala sequence types.)
The first element of a list is its head, the rest is its tail.
The most common methods of lists are the common methods of all sequences.
You can write ::: instead of ++ to concatenate two lists (to keep the syntax similar to the cons-operator).