Scala (2-1) Collections (Array and List)

1. Array:

Arrays are mutable which is used to store a fixed-size sequential collection of elements of the same type.

The following example shows how to create an array to hold 3 strings.

val names = new Array[String](3)

We can assign the new value to the element of the array.

names(0) = "Ben"
names(1) = "Alice"
names(2) = "Vick"

Note that the arrays in Scala are accessed by placing the index inside parentheses.

We can iterate through the Array with a for...in loop.

for (name <- names ) {
    println(name) // do something
}

2. List:

Scala's List, differs from Java’s List type which is always immutable.

val names = List("Alice", "Ben", "Vick")
println(names(2))
names(1) = "Beny" // error

If we want to concatenate the lists, we need to create a new variable.

val groupA = List("Bob", "Alice")
val groupB = List("Tom", "Kitty")
val newGroup = groupA ::: groupB // concatenate groupA with groupB
println(newGroup)

Scala’s List is designed to enable a functional style of programming.

val squareSize = List(5, 10, 30)
val squareArea = squareSize.map( (x) => x * x )
println(squareArea)

List.map() will iterate through the elements in the List and apply the function to the element.

List.map() receives a function as a parameter. (x) => x * x is a lambda expression in Scala which means input a x and return x * x (we will write other articles to talk about the detail of the lambda expression).

List.filter() is another useful function. See the following syntax:

val numLst = List(1,2,3,4,5,6,7)
val evenLst = numLst.filter( (x) => x%2 == 0 )
println(evenLst) // List(2,4,6)

List.filter() also receives a function as a parameter which filters the elements in the List if the lambda expression return false.


留言

熱門文章