Home

Search

Scala Initialize List: List.newBuilder, List.emptyBuild up elements in Lists with operators and constructors. Use List.empty and newBuilder.
dot net perls

Initialize list. In Scala lists are immutable. This presents a problem when creating lists. We sometimes need complicated initialization logic.

List

Syntax. 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.

Builder example. 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.

Tip We need to specify the type of elements as part of the List.newBuilder function call. Here I use Int.

And We can add elements to the Builder's internal buffer by using the addition operator. With result() we get the final immutable list.

Scala program that uses List.newBuilder
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)

Combine two lists. 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.

Scala program that combines two lists
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)

New element. 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.

Warning If we use "::" with another list, that entire list (not its individual elements) will be placed in the head of the new list.

Scala program that initializes list with new element
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).

String

Scala program that uses List.empty
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)

A summary. Lists are immutable in Scala, so initializing lists is critical. With List.newBuilder and List.empty we can begin initializing lists with ease.

Home
© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.