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

List Basics

In this page:

  1. List Basics

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)
}
🔒

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.