Scala Collections - Buffers

Question Click to View Answer

What does the following code print?

val leaders = collection.mutable.Buffer("Reykon")
leaders += "obama"
println(leaders)

ArrayBuffer(Reykon, obama) is printed.

leaders is a mutable list of items, commonly known as a buffer in Scala. Collections created with List or collection.immutable.List are immutable and items cannot be appended to immutable collections.

What does the following code print?

val stuff = collection.mutable.Buffer("blue")
stuff += 44
println(stuff)

This code throws an error. Strings are the only item that can be appended to the stuff buffer.

You cannot append an integer to a buffer with the scala.collection.mutable.Buffer[String] type.

What does the following code print?

val coolCreatures = collection.mutable.Buffer()
coolCreatures += "spongebob"
println(coolCreatures)

This code throws an error. coolCreatures is instantiated without any elements, so the Scala compiler assumes that all elements of the buffer will be of type Nothing. "spongebob" is a string (it's not of type nothing), so it cannot be added to the coolCreatures buffer. A type should be specified when creating an empty buffer to avoid this error.

val coolCreatures = collection.mutable.Buffer[String]()
coolCreatures += "spongebob"
println(coolCreatures)

What does the following code print?

val turtles = collection.mutable.Buffer("mikey", "leo")
turtles(0) = "donny"
println(turtles)

ArrayBuffer(donny, leo) is printed.

The buffer is initially defined with mikey as the first element and leo as the second element. turtles(0) = "donny" mutates the turtles buffer, so donny is the first element.

What does the following code print?

val fruits = collection.mutable.Buffer("apple", "orange")
println(fruits.toList)

List(apple, orange) is printed.

The fruits val is assigned to a mutable buffer. The buffer is converted to an immutable list and printed.

What does the following code print?

val veggies = collection.mutable.Buffer("carrots")
veggies += "peas"
println(veggies.last)

peas is printed.

The veggies buffer contains the string carrots and the string peas. The last element of the buffer is printed.