Skip to content
Lesson 5 of 11

Step 1 of 5 · Reading · ~1 min

Learn

Collections

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.

Printing a list as one line

println(xs) shows Scala's own rendering of the list, brackets and commas included. To print just the elements, join them with mkString:

val xs = List(5, 4, 3)
println(xs)                  // List(5, 4, 3)
println(xs.mkString(" "))    // 5 4 3
println(xs.mkString(", "))   // 5, 4, 3

fold is not an alternative here. Folding a List[Int] makes the accumulator an Int, so xs.fold(_ + _) gives you the sum; trying to fold the same list into a String fails to compile because the accumulator type no longer matches the element type.

Your exercise

Sort Descending wants one line of space-separated numbers, so the last step is mkString(" ") over sortWith(_ > _) (or sorted.reverse). Printing the list itself is the mistake the grader catches: it emits List(5, 4, 3, 1, 1), not 5 4 3 1 1.

Up nextMaps and SetsCollections

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…