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
val potCount = 6infiereInt;val soilLiters = 2.5,Double;val species = "monstera",String.val wateringDays = List(1, 4, 8, 11)toma su tipo de los valores;dosesunifica los literales enList[Double].def litersFor(pots: Int): Doublesí anota su tipo de retorno: la firma es de lo que depende el resto del código.
Palabras clave y builtins usados aquí
defval
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.
Paso 2 de 3 en Valores y tipos; paso 2 de 27 en Fundamentos del lenguaje.