Type inference in Scala
The compiler reads Int, Double, String and List types off the values you write.
// The compiler reads the type off the right-hand side.
val potCount = 6 // Int
val soilLiters = 2.5 // Double
val species = "monstera" // String
// The element type comes from the values in the list.
val wateringDays = List(1, 4, 8, 11) // List[Int]
// Numeric literals harmonize, so this is not List[AnyVal].
val doses = List(0.5, 1, 1.75) // List[Double]
// Annotate what other code depends on: a return type is part
// of the signature, so state it even when it is obvious.
def litersFor(pots: Int): Double = pots * soilLiters
def plantSummary: String = species + " x " + potCount
def careDemo(): Unit =
println(s"$plantSummary: ${litersFor(wateringDays.length)}")
println(doses.sum)
How it works
val potCount = 6infersInt,val soilLiters = 2.5infersDouble, andval species = "monstera"infersString.val wateringDays = List(1, 4, 8, 11)takes its element type from the values, andval doses = List(0.5, 1, 1.75)harmonizes the literals into aList[Double].def litersFor(pots: Int): Doublestill annotates its return type, because the signature is what other code depends on.
Keywords and builtins used here
DoubleIntListStringUnitcareDemodeflitersForplantSummaryval
The run, in numbers
- Lines
- 20
- Characters to type
- 704
- Tokens
- 98
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 74 seconds.
Step 2 of 3 in Values & types, step 2 of 27 in Language basics.