Skip to content

Instantly share code, notes, and snippets.

@dirkmc
Created December 22, 2011 07:35
Show Gist options
  • Save dirkmc/1509387 to your computer and use it in GitHub Desktop.
Save dirkmc/1509387 to your computer and use it in GitHub Desktop.
Creating Lists with Scala

Scala encourages developers to create data structures that cannot be modified.

To create an immutable list:

val fruits = List("apple", "pear", "orange")

Concatenate two lists:

val summerFruits = List("banana", "orange")
val winterFruits = List("strawberry", "apple", "pear")
val fruits = summerFruits :: winterFruits
// fruits is now List("banana", "orange", "strawberry", "apple", "pear")

If you do need to be able to modify a list, you can create a mutable list like this:

val seasonFruits = scala.collection.mutable.ListBuffer("banana", "orange")
if(month > 3 && month < 9) { // We're in Argentina, not the USA :)
  seasonFruits(0) = "strawberry"
  seasonFruits(1) = "pear"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment