Scala Lists

By: Stephen Patrick | 07 Aug 2016 | Category: Scala Language Basics

Related Contents

Scala Lists

Scala provides a List collection type scala.List. Like an Array the list data structure contains a sequence of elements. However, there is an important difference between a Scala Array and a Scala List. The Scala List data type is an immutable data type, while the Scala Array is a mutable data type. This fact is important to understand when writing programs in Scala. Moreover, an important aspect of functional programming is that a function should have no side effects. In this sense List is designed to work with functional code as it is an immutable type.

Below is some examples of creating Lists in Scala

val intList = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

val intList  = List[Int](1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

val intList : List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

val intList : List[Int] = List[Int](1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

We can also prepend a new item to the beginning of a List using cons ::. This will return a new List.

val intList = List(2, 3)
val newList = 1 ::  intList


Outputs:
newList: List[Int] = List(1, 2, 3)

We can also use the above to create a new List. We can create a List with two basic structures a tail and cons.

val newList = 1 :: 2 :: 3 :: Nil

Above Nil is a shorthand for an empty list. In this case we prepend 3, 2, and 1 to the empty list.

Scala Common List Operations

Concatenating Lists

A List can be concatenated with another List.

val intList = List(1, 2, 3)
val tailList = List(4, 5, 6)
val newList = intList ::: tailList

Outputs:
newList: List[Int] = List(1, 2, 3, 4, 5, 6)

Scala List Head

We can get the first element of a List using the head method.

val intList = List(1, 2, 3)
intList.head

Outputs:
1

Scala List Tail

We can get the last element of a List using the tail method.

val intList = List(1, 2, 3)
intList.tail

Outputs:
3

Scala List IsEmpty

We can test if a Scala List is empty

val intList = List(1, 2, 3)
intList.isEmpty

val emptyList = Nil
emptyList.isEmpty


Outputs:
false
true

Scala Reverse List

We can reverse a Scala List using the reverse method. In fact reversing a list in combination with prepend is a more efficient means of appending elements to a list.

val intList = List(1, 2, 3)
intList.reverse


Outputs:
List(3, 2, 1)