In Scala lists are immutable. This presents a problem when creating lists. We sometimes need complicated initialization logic.
List.newBuilder
can be used to add many values into a temporary collection and then convert that to a list. We can initialize lists by combining 2 lists or adding elements.
Here we create a list with the List
constructor syntax (a list literal). Then we use List.newBuilder
to create the same list with a Builder.
List.newBuilder
function call. Here I use Int
.result()
we get the final immutable list.object Program { def main(args: Array[String]): Unit = { // Create a list with values. val numbers = List(10, 11, 12) println(numbers) // Create a list with a Builder. val builder = List.newBuilder[Int] builder += 10 builder += 11 builder += 12 val numbers3 = builder.result() println(numbers3) } }List(10, 11, 12) List(10, 11, 12)
Sometimes the easiest way to initialize a list is to combine two (or more than two) lists that already exist. Here we create two small lists and then merge them.
object Program { def main(args: Array[String]): Unit = { // Add two lists together. val numbers1 = List(13, 14) val numbers2 = List(15, 16) val numbers3 = numbers1 ::: numbers2 println(numbers3) } }List(13, 14, 15, 16)
Here we create a list by taking an existing list and adding another element to its start. This changes the head of the list. This only works with individual elements.
object Program { def main(args: Array[String]): Unit = { // Initialize a list by placing an element at its start. val numbers1 = List(100, 200) val numbers2 = 50 :: numbers1 println(numbers2) } }List(50, 100, 200)
List.empty
This can be used to initialize lists. We can place new elements alongside List.empty
and initialize a new list. We must specify the type of elements (like String
).
object Program { def main(args: Array[String]): Unit = { // Initialize an empty list and add an element to it. val numbers1 = List.empty[String] val numbers2 = "cat" :: numbers1 println(numbers2) } }List(cat)
Lists are immutable in Scala, so initializing lists is critical. With List.newBuilder
and List.empty
we can begin initializing lists with ease.