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
1
//create a list from known elements
2
val a: List[Int] = List(1, 2, 3, 4)
3
//a: List[Int] = List(1, 2, 3, 4)
4
​
5
//create an empty list
6
val b:List[Int]=List[Int]()
7
//Check if it is empty
8
println(b==Nil)
9
//add element into it
10
val c:List[Int]=1::2::3::4::b
11
//concat 2 list
12
val d:List[Int]=a++c
13
​
14
/*
15
true
16
b: List[Int] = List()
17
c: List[Int] = List(1, 2, 3, 4)
18
d: List[Int] = List(1, 2, 3, 4, 1, 2, 3, 4)
19
*/
Copied!

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
1
//Create a Seq if you have elements
2
val s:Seq[Int]=Seq(1,2,3,4)
3
//s: Seq[Int] = List(1, 2, 3, 4)
4
//Create an empty Seq
5
val t:Seq[Int]=Seq[Int]()
6
//t: Seq[Int] = List()
7
t==Nil
8
//res5: Boolean = true
9
//Add elements to Seq, prepend
10
val u:Seq[Int]=t:+1:+2:+3:+4
11
//u: Seq[Int] = List(1, 2, 3, 4)
Copied!
​
Last modified 1yr ago
Copy link
Contents
List
Seq