typestar

Inferencia de tipos en Scala

El compilador deduce los tipos Int, Double, String y List de los valores que escribes.

// 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)

Cómo funciona

  1. val potCount = 6 infiere Int; val soilLiters = 2.5, Double; val species = "monstera", String.
  2. val wateringDays = List(1, 4, 8, 11) toma su tipo de los valores; doses unifica los literales en List[Double].
  3. def litersFor(pots: Int): Double sí anota su tipo de retorno: la firma es de lo que depende el resto del código.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
20
Caracteres a escribir
704
Tokens
98
Ritmo de tres estrellas
80 tpm

Al ritmo de tres estrellas de 80 tokens por minuto, este intento toma unos 74 segundos.

Escribe este fragmento

Paso 2 de 3 en Valores y tipos; paso 2 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →