Scala List Class
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
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
Vector performance information.)
List class basics
// creating a List val nums = List(1, 2, 3, 4, 5) // accessing List elements nums(0) nums(1) // accessing List elements in a for-loop for n <- nums do println(n) // creating a new list from an existing list, // using a for-expression val names = List("bert", "ernie") val capNames = for name <- names yield name.capitalize // the `map` method is the same as that for-expression val capNames = names.map(_.capitalize)
For many more
List class details, see my Scala List class examples page.