Skip to main content
Please wait...
The Scala List is an implementation of the Scala Seq
06 Apr, 2025

Learn Scala: Scala List is an implementation of Scala Seq

In Scala, List is an immutable, singly linked list that is a concrete implementation of the Seq trait. Lists are efficient for sequential access and pattern matching.  Here's an example of a boolean list: 

val boolList = List(true, false, true, false) 
  

This creates a list containing boolean values.  An example of a string list: 

val stringList: List[String] = List("Scala", "Java", "Python", "Ruby") 
  

This creates a list containing elements of type String.  To create a Scala list without using the companion object, you can use the :: (cons) operator and Nil: 

val a = 1 :: 2 :: 3 :: 4 :: Nil 
  

This creates the same list as List(1, 2, 3, 4) but without explicitly calling the List companion object. The :: operator prepends elements to the list, and Nil represents the empty list.  Here's an example that iterates over combinations of elements in a list: 

val a: List[Int] = List(1, 2, 3, 4) 
val combinations = for { 
  x <- a 
  y <- a 
} yield (x, y) 
 
combinations.foreach(println) 
  

This code creates a list containing elements 1, 2, 3, and 4, then generates all possible combinations of these elements and prints them.  Finally, here's an example with a filter. The resulting list will only include list elements that satisfy the condition of being an even number: 

val a = List(1, 2, 3, 4) 
val filteredList = a.filter(_ % 2 == 0) 
println(filteredList) 
  

This filters the list a to include only even numbers, resulting in List(2, 4).