Reading — step 1 of 5
Learn
~1 min readCollections
Scala's standard collections are immutable by default. The List type is a singly-linked list — fast prepend, O(n) random access:
val xs = List(1, 2, 3)
val ys = 0 :: xs // prepend: List(0, 1, 2, 3)
val zs = xs ::: List(4, 5) // concat: List(1, 2, 3, 4, 5)
xs.head // 1
xs.tail // List(2, 3)
xs.length // 3
xs(0) // 1 (random access)
For random access use Vector (effectively constant-time indexed):
val v = Vector(1, 2, 3, 4, 5)
v(2) // 3
v :+ 6 // append
6 +: v // prepend
Mutable variants exist in scala.collection.mutable.{ListBuffer, ArrayBuffer} — use sparingly. Idiomatic Scala builds new collections rather than mutating.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…