← Back to Scala Course | Chapter 6: Collections Basics | Lesson 1 of 8

List Basics

A List is a chain of items that cannot be changed once it is made, like a train of linked cars. To get a different list you build a new one.

In this page:

  1. List Basics
Syntax
scala
val list = List(value1, value2, value3)
val newList = value0 :: list
val joined = list1 ::: list2

List Basics

A Scala List is an immutable, singly-linked sequence, created with List(1, 2, 3). Being immutable, operations like adding an element return a *new* list rather than modifying the original.

:: ("cons") prepends an element to the front of a list efficiently, and Nil represents the empty list.

Note: 1 :: 2 :: 3 :: Nil is an equivalent, more explicit way to construct List(1, 2, 3) using cons.

Example: List Basics

markup
object Main extends App {
  val numbers = List(1, 2, 3, 4)
  val withZero = 0 :: numbers

  println(numbers)
  println(withZero)
  println(numbers.length)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to change a list with numbers(0) = 5, when a List is immutable and has no update.
  2. Expecting numbers :+ 5 or 0 :: numbers to modify numbers, when they return a new list.
  3. Using list(i) in a loop for long lists, which is slow because a List is a linked list with linear access.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.