Mutable variables (var) and type inference

Introduction to Scala

David Venturi

Curriculum Manager, DataCamp

Scala has two kinds of variables

val (immutable)

  • can't be reassigned

Four of hearts

scala> val fourHearts: Int = 4
fourHearts: Int = 4

var (mutable)

  • can be reassigned

Ace of spades

scala> var aceSpades: Int = 1
aceSpades: Int = 1
Introduction to Scala

Reassigning a val produces an error

scala> val fourHearts: Int = 4
fourHearts: Int = 4
scala> val fourHearts = 5
<console>:12: error: reassignment to val
       fourHearts = 5
                  ^
Introduction to Scala

Reassigning a var works

scala> var aceSpades: Int = 1
aceSpades: Int = 1
scala> aceSpades = 11
aceSpades: Int = 11
Introduction to Scala

Pros and cons of immutability

Pros

  • Your data won't be changed inadvertently
  • Your code is easier to reason about
  • You have to write fewer tests

Cons

  • More memory required due to data copying
Introduction to Scala

Scala nudges us towards immutability

Bear nudging another bear

The word "immutability"

Introduction to Scala

Type inference is powerful

scala> val fourHearts: Int = 4
fourHearts: Int = 4
scala> var aceSpades: Int = 1
aceSpades: Int = 1
scala> val fourHearts = 4
fourHearts: Int = 4
scala> var aceSpades = 1
aceSpades: Int = 1
Introduction to Scala

Semicolons

scala> val fourHearts = 4
fourHearts: Int = 4
scala> var aceSpades = 1
aceSpades: Int = 1
Introduction to Scala

Semicolons

scala> val fourHearts = 4;
fourHearts: Int = 4
scala> var aceSpades = 1;
aceSpades: Int = 1
Introduction to Scala

Semicolons

scala> val fourHearts = 4
fourHearts: Int = 4
scala> var aceSpades = 1
aceSpades: Int = 1
Introduction to Scala

Let's practice!

Introduction to Scala

Preparing Video For Download...