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
val ferryName = "Islander"binds once, whilevar seatsSold = 0is the single binding that gets reassigned.val seatsPerDeck: Int = 48spells the type out;val deckCount = 3leaves it to the compiler.val totalSeats = seatsPerDeck * deckCountis computed from other vals, andsellSeatsupdates the var withseatsSold += count.
Keywords and builtins used here
IntUnitdefferryReportseatsLeftsellSeatsvalvar
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.
Step 1 of 3 in Values & types, step 1 of 27 in Language basics.