typestar

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

  1. val potCount = 6 infers Int, val soilLiters = 2.5 infers Double, and val species = "monstera" infers String.
  2. val wateringDays = List(1, 4, 8, 11) takes its element type from the values, and val doses = List(0.5, 1, 1.75) harmonizes the literals into a List[Double].
  3. def litersFor(pots: Int): Double still annotates its return type, because the signature is what other code depends on.

Keywords and builtins used here

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.

Type this snippet

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

← Previous Next →