February 2018
Intermediate to advanced
552 pages
13h 46m
English
In Scala, List has an operator ::, which is known as the Cons operator. It is useful to add new elements at the beginning of the List. Here, Cons is short for construct the new List object.
Let us explore the Cons operator with some simple examples (here :: is a double colon):
scala> var numbersList = List (1,2,3)
numbersList: List[Int] = List(1, 2, 3)
scala> numbersList = numbersList :: 4
<console>:11: error: value :: is not a member of Int
numbersList = numbersList :: 4
^
We cannot use the Cons operator to add a new element at the end of the List. It accepts it only to add it at the beginning of the List:
scala> numbersList = 4 :: numbersList numbersList: List[Int] = List(4, 1, 2, 3) scala> numbersList = 6 :: 5 ...
Read now
Unlock full access