Scala Wonderland: Lists

In functional style methods should not have side effects. A consequence of this philosophy is that List is immutable in Scala. Construction of a List is simple.

val abc = List("a", "b", "c")

There is one trick in the previous code. A common trick in Scala. It invokes method named apply on List companion object. Companion objects will be explained later. Until then you may look at this method as a static factory method that returns new instance of List. Following code does the same:

val abc = List.apply("a", "b", "c")

Very convenient is usage of the list concatenation “cons” operator ::. It prepands new element at the beginning of an list. Another useful object is Nil which represents an empty list. To construct the same list using cons you may write following.

val abc = "a" :: "b" :: "c" :: Nil

Pretty unusual to prepend a new element instead of appending it, right? The reason is that List is implemented as a linked list. Which means that prepending takes constant time, but appending is linear.
The last magic in this simple excercise is that the cons operator is right-associative. General rule in Scala says that if name of an operator ends with colon “:”, then it is executed on the right operand. Otherwise usual left-associativity is applied. Yet another equivalent piece of code.

val abc = Nil.::("c").::("b").::("a")

Immutability, the apply method, companion object, prepending, linked list, right associativity. Isn’t it too much for such a trivial code? There is a lot of magic in this wonderland.

Leave a Reply