typestar

val & var in Scala

A ferry seat count held in val bindings, with one var for the number that really changes.

// A val is bound once; a var can be reassigned later.
val ferryName = "Islander"
var seatsSold = 0

// Write the type out or leave it to the compiler.
val seatsPerDeck: Int = 48
val deckCount = 3

// A val may be computed from other vals.
val totalSeats = seatsPerDeck * deckCount

def sellSeats(count: Int): Unit =
  seatsSold += count

def seatsLeft: Int = totalSeats - seatsSold

def ferryReport(): Unit =
  sellSeats(52)
  println(s"$ferryName: $seatsLeft of $totalSeats seats left")

How it works

  1. val ferryName = "Islander" binds once, while var seatsSold = 0 is the single binding that gets reassigned.
  2. val seatsPerDeck: Int = 48 spells the type out; val deckCount = 3 leaves it to the compiler.
  3. val totalSeats = seatsPerDeck * deckCount is computed from other vals, and sellSeats updates the var with seatsSold += count.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
482
Tokens
73
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 55 seconds.

Type this snippet

Step 1 of 3 in Values & types, step 1 of 27 in Language basics.

Next →