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:
Syntax
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
object Main extends App {
val numbers = List(1, 2, 3, 4)
val withZero = 0 :: numbers
println(numbers)
println(withZero)
println(numbers.length)
}
Login to try C/C++/Java/PHP code in the editor
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
- Trying to change a list with
numbers(0) = 5, when aListis immutable and has noupdate. - Expecting
numbers :+ 5or0 :: numbersto modifynumbers, when they return a new list. - Using
list(i)in a loop for long lists, which is slow because aListis a linked list with linear access.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: