Learn Scala - Lists

Question Click to View Answer

What does the following code print?

val people = List("lebron", "messi", "ke$ha")
println(people.size)

3 is printed.

people is an immutable singly linked list. The size method is available on all collections and returns the number of elements in the collection.

What does the following code print?

val lyrics = List("all", "that", "i", "know")
println(lyrics.head)

all is printed.

The head method returns the first element in a list.

What does the following code print?

val future = List("soon", "i'll", "be", "60 years old")
println(future.tail)

List(i'll, be, 60 years old) is printed.

The tail method returns all the elements in list except the first element.

What does the following code print?

val spanish = List("como", "j", "balvin", "va")
println(s"${spanish(1)} ${spanish(2)} bobo")

j balvin bobo is printed.

spanish(1) gets the second element in the list and spanish(2) gets the third element in the list. String interpolation is used to generate the output string.

What does the following code print?

val numbers = List(11, 22, 33)
var total = 0
for (i <- numbers) {
  total += i
}
println(total)

66 is printed.

The for loop iterates over all the elements in the numbers list and keeps a running total of the sum in the total variable. total is then printed.

What does the following code print?

val odds = List(3, 5, 7)
var result = 1
odds.foreach( (num: Int) => result *= num )
println(result)

105 is printed.

The foreach method takes an anonymous function as an argument. The loop multiplies all the numbers in the array and then the result is printed.

What does the following code print?

val singers = List("shakira", "nicky jam")
var result = singers.map( (s: String) => s"$s is cool" )
println(result)

List(shakira is cool, nicky jam is cool) is printed.

The map method takes an anonymous function as an argument and returns a new list.

Double all the numbers in the following nums list.

val nums = List(4, 10, 30)

The map method is used to iterate over all the numbers in nums, double them, and return a new list.

println( nums.map( (n: Int) => n * 2 ) )

What does the following code print?

val evens = List(2, 4, 8)
println {
  evens.foldLeft(0) { (memo: Int, y: Int) =>
    memo + y
  }
}

14 is printed.

The foldLeft method can be used to combine every element in a list into a single result. The memo variable is initially set to 0 and accumulates the running sum. The y variable is assigned to each element in the evens list during the iteration. This code sums all the numbers in the evens list, basically 0 + 2 + 4 + 8