Effective Scala, part 5 - collections
Posted on in Effective Scala series
Operations on collections can be classified into:
-
construct ops (
::
,+:
,:+
,+
,++
); -
query ops (
size
,empty
,head
,tail
,find
,filter
); and -
transform ops (
map
,fold
)
Infix construct operators
There are a shitload of them, most of them with low recall value to a beginner.
Immutable operators
-
::
to prepend to a List.1 :: List.empty
-
+:
to prepend to aSequence
collection, includingList
.1 +: mutable.ArrayBuffer(2, 3)
-
:+
to append to aSequence
collection -
+
to add a (key, value) tuple to a Map -
++
constructs a new collection out of two collections.Map((1, "1"), (2, "2")) ++ Map((4, "4"))
Mutable operators
-
+=:
to prepend to aSequence
collection -
+=
to append to aSequence
collection -
++=
concatenates two collections, mutates the first one.
List
A list is constructed from right to left:
1 :: 2 :: 3 :: Nil
Option
Option is actually a collection of zero or one element.
This explains why Option type has a map
or filter
operations even in OCaml.
No indexed access (opt(0)
) though, understandably.