11.1. Different Ways to Create and Populate a List
Problem
You want to create and populate a List
.
Solution
There are many ways to create and initially populate a List
:
// 1 scala>val list = 1 :: 2 :: 3 :: Nil
list: List[Int] = List(1, 2, 3) // 2 scala>val list = List(1, 2, 3)
x: List[Int] = List(1, 2, 3) // 3a scala>val x = List(1, 2.0, 33D, 4000L)
x: List[Double] = List(1.0, 2.0, 33.0, 4000.0) // 3b scala>val x = List[Number](1, 2.0, 33D, 4000L)
x: List[java.lang.Number] = List(1, 2.0, 33.0, 4000) // 4 scala>val x = List.range(1, 10)
x: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9) scala>val x = List.range(0, 10, 2)
x: List[Int] = List(0, 2, 4, 6, 8) // 5 scala>val x = List.fill(3)("foo")
x: List[String] = List(foo, foo, foo) // 6 scala>val x = List.tabulate(5)(n => n * n)
x: List[Int] = List(0, 1, 4, 9, 16) // 7 scala>val x = collection.mutable.ListBuffer(1, 2, 3).toList
x: List[Int] = List(1, 2, 3) // 8 scala>"foo".toList
res0: List[Char] = List(f, o, o)
The first two approaches shown are the most common and
straightforward ways to create a List
. Examples 3a and 3b show how you can
manually control the List
type when
your collection has mixed types. When the type isn’t manually set in
Example 3a, it ends up as a List[Double]
, and in 3b it’s manually set to
be a List[Number]
.
Examples 4 through 6 show different ways to create and populate a
List
with data. Examples 7 and 8 show
that many collection types also have a toList
method that converts their data to a
List
.
Going back ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.