home search about rss feed twitter ko-fi

List Class, Part 2 (Scala 3 Video)

Scala List Class

The List class is an immutable, singly-linked list. You can use it (a) when you need a small, immutable sequential collection, and (b) when you need a larger sequence, and you’ll only be prepending elements, and accessing its head and tail elements (using methods like map and filter, which always begin at the first element and start marching through each subsequent element is also okay).

If you want an immutable sequence class where you want fast, random access to any element in the sequence, use Vector instead. (See the video for List and Vector performance information.)

Creating a List

Create a List just like a Vector and other sequences:

// List
val a = List(1, 2, 3)

// others
val b = Vector(1, 2, 3)
val c = Set(1, 2, 3)
val d = ArrayBuffer(1, 2, 3)

You can also create a List with the Lisp style:

val a = List(1, 2, 3)          // the “normal” approach
val b = 1 :: 2 :: 3 :: Nil     // the Lisp style

Updating a List

The List type is immutable, so when you want to update its elements, you must assign the results to a new variable:

val a = List(1, 2, 3)
val b = List(4, 5, 6)
val c = a ++ b

// updating elements
val a = List(1, 2, 3)
val b = a.updated(index=0, elem=10)   // b: List(10, 2, 3)
val c = b.updated(1, 20)              // c: List(10, 20, 3)

// deleting elements
val a = List(5, 1, 4, 3, 2)
val b = a.filter(_ > 2)   // b: List(5, 4, 3)
val b = a.take(2)         // b: List(5, 1)
val b = a.drop(2)         // b: List(4, 3, 2)

Prepending elements

When you work with a List, the preferred approach is to prepend elements:

// prepending one element
val a = List(3)    // List(3)
val b = 2 :: a     // List(2, 3)
val c = 1 :: b     // List(1, 2, 3)

// prepending a List to a List
val a = List(3, 4)           // a: List(3, 4)
val b = List(1, 2) ::: a     // b: List(1, 2, 3, 4)

Working with List head and tail elements

match expressions work well with List, because it’s easy to break a List into its head and tail components:

// match expressions (works well)
def sum(xs: List[Int]): Int = xs match
    case Nil => 0
    case head :: tail => head + sum(tail)

More information

For many more List class details, see:

Update: All of my new videos are now on
LearnScala.dev