Jayesh Bhoot's Ghost Town

Effective Scala, part 5 - collections§

Posted on in

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 a Sequence collection, including List. 1 +: mutable.ArrayBuffer(2, 3)
  • :+ to append to a Sequence 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 a Sequence collection
  • += to append to a Sequence 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.

Post author's photo Written by Jayesh Bhoot

§