List/Seq

List

The Scala List is a sequence of elements, implemented as a linked list. Lists support efficient addition of new elements at the front.

Unlike Python list, which is mutable; Scala List is immutable

//create a list from known elements
val a: List[Int] = List(1, 2, 3, 4)
//a: List[Int] = List(1, 2, 3, 4)

//create an empty list
val b:List[Int]=List[Int]()
//Check if it is empty
println(b==Nil)
//add element into it
val c:List[Int]=1::2::3::4::b
//concat 2 list
val d:List[Int]=a++c

/*
true
b: List[Int] = List()
c: List[Int] = List(1, 2, 3, 4)
d: List[Int] = List(1, 2, 3, 4, 1, 2, 3, 4)
*/

Seq

A base trait for sequences. Sequences are special cases of iterable collections of class Iterable. List is the implementation of Seq.

Similar to List, but some difference when operating such as adding elements to existing Seq

//Create a Seq if you have elements
val s:Seq[Int]=Seq(1,2,3,4)
//s: Seq[Int] = List(1, 2, 3, 4)
//Create an empty Seq
val t:Seq[Int]=Seq[Int]()
//t: Seq[Int] = List()
t==Nil
//res5: Boolean = true
//Add elements to Seq, prepend
val u:Seq[Int]=t:+1:+2:+3:+4
//u: Seq[Int] = List(1, 2, 3, 4)

Last updated