Arrays

Introduction to Scala

David Venturi

Curriculum Manager, DataCamp

Collections

  • Mutable collections
    • can be updated or extended in place
  • Immutable collections
    • never change
Introduction to Scala

Array

  • Mutable sequence of objects that share the same type
  • Parameterize an array: configure its types and parameter values
  • Initialize elements of an array: give the array data
scala> val players = Array("Alex", "Chen", "Marta")
players: Array[String] = Array(Alex, Chen, Marta)
Introduction to Scala

Array

  • Parameterize an array: configure its types and parameter values
scala> val players = new Array[String](3)
players: Array[String] = Array(null, null, null)
  • Type parameter: String
  • Value parameter: length which is 3
Introduction to Scala

Array

  • Parameterize an array: configure its types and parameter values
scala> val players: Array[String] = new Array[String](3)
players: Array[String] = Array(null, null, null)
  • Type parameter: String
  • Value parameter: length which is 3
Introduction to Scala

Array

  • Parameterize an array: configure its types and parameter values
  • Initialize elements of an array: give the array data
scala> players(0) = "Alex"
scala> players(1) = "Chen"
scala> players(2) = "Marta"

scala> players
res3: Array[String] = Array(Alex, Chen, Marta)
Introduction to Scala

Arrays are mutable

scala> val players = Array("Alex", "Chen", "Marta")
players: Array[String] = Array(Alex, Chen, Marta)
scala> players(0) = "Sindhu"
res5: Array[String] = Array(Sindhu, Chen, Marta)
Introduction to Scala

Arrays are mutable

scala> val players = Array("Alex", "Chen", "Marta")
players: Array[String] = Array(Alex, Chen, Marta)
scala> players(0) = 500
<console>:13: error: type mismatch;
 found   : Int(500)
 required: String
       players(0) = 500
Introduction to Scala

Recommendation: use val with Array

scala> var players = Array("Alex", "Chen", "Marta")
players: Array[String] = Array(Alex, Chen, Marta)

Elements can change

scala> players(0) = "Sindhu"

players can be reassigned

scala> players = new Array[String](5)
scala> players
res2: Array[String] = Array(null, null, null, null, null)
Introduction to Scala

Scala nudges us towards immutability

Polar bear nudging a panda bear

The word "immutability"

Introduction to Scala

The Any supertype

scala> val mixedTypes = new Array[Any](3)
mixedTypes: Array[Any] = Array(null, null, null)
scala> mixedTypes(0) = "I like turtles"
scala> mixedTypes(1) = 5000
scala> mixedTypes(2) = true

scala> mixedTypes
res3: Array[Any] = Array(I like turtles, 5000, true)
Introduction to Scala

Let's practice!

Introduction to Scala

Preparing Video For Download...