Learning Scala: Array and List


Array

Define an array

  • var myArray = new Array[Int](3) (the type of myArray is inferred)
  • var myArray:Array[Int] = new Array[Int](3) (explicit type declaration)
  • var myArray = Array.apply(1, 2, 3)
  • var myArray = Array(1, 2, 3)

Accessing an element in an array

  • myArray(0)
  • myArray.apply(0)

Changing an element in an array

  • myArray(0) = 100
  • myArray.update(0, 100)

List

Define a list

  • var list = List(1, 2, 3)

Append an element to a list

  • list = 1 :: list

Some useful list methods

  • list.map(element => element + 1) (increments each list element by 1)
  • list.exists(element => element < 0) (determines whether the list contains a negative element)
  • list.filter(element => (element % 2) == 0) (filters even numbers)
  • list.isEmpty (self explanatory)
  • list.head (returns the first element of a list)
  • list.last (returns the last element of a list)
  • list.reverse (returns a list with its elements in reverse order)
  • list.remove(element => (element % 3) == 0) (remove all multiples of 3 from the list)
Advertisements