Tuesday, July 26, 2011

Scala: Array vs List

Arrays are mutable objects, you can't change the length of an array after it is instantiated. You can change its element values.

val numNames = Array("zero", "one", "two") // is the same as below
val numNames2 = Array.apply("zero", "one", "two")

numNames.update(0, "ZZZ") // update array element

For an immutable sequence of objects that share the same type you can
use Scala’s List class. As with arrays, a List[String] contains only
strings. Scala’s List, scala.List, differs from Java’s java.util.List
type in that Scala Lists are always immutable (whereas Java Lists can be
mutable). More generally, Scala’s List is designed to enable a functional
style of programming.

val oneTwoThree = List(1, 2, 3)

No comments: