Learn Java for Web Development

(Tina Meador) #1
APPENDIX C: Introduction to Scala 427

operations that simulate additions, removals, or updates, but those operations will in each case
return a new collection and leave the old collection unchanged. Scala has a rich collections
library. The most commonly used collections are lists, sets, and maps, which are explained in the
following sections. You can find details on Scala’s collection library at http://docs.scala-lang.org/
overviews/collections/introduction.html.


Lists

Lists are immutable, which means the elements of a list cannot be changed by assignment. The type
of a list that has elements of type T is written as List[T], as shown here:


val numberList: List[Integer] = List(1, 2, 3)


Listing C-5 illustrates how to create and use an immutable list.


Listing C-5. Creating an Immutable List


val list = List(1, 2, 3, 2, 3)
println (list.head)
println(list.tail)
println(list.length)
println(list.max)
println(list.min)
println(list.sum)
println(list.sorted)
println(list.reverse)


head --- 1


tail --- List(2, 3, 2, 3)


length --- 5


max --- 3


min --- 1


sum --- 11


sorted --- List(1, 2, 2, 3, 3)


reverse--- List(3, 2, 3, 2, 1)


Scala defines only an immutable list. However, it also defines some mutable list types, such as
ArrayBuffer. Listing C-6 illustrates how to create a mutable list.


Listing C-6. Creating a Mutable List


import collection.mutable
val list = mutable.ArrayBuffer(1, 2, 3, 2, 3)
assert (list.length == 5)

Free download pdf