Case classes en Scala
Un registro Lighthouse con impresión e igualdad generadas, desarmado por un match.
// a case class is an immutable record whose fields are public vals
case class Lighthouse(name: String, heightM: Int, flashSec: Int)
// no new keyword is needed to build one
val portland: Lighthouse = Lighthouse("Portland", 41, 5)
// toString is generated, printing the class name and the fields
val printed: String = portland.toString
// equality compares the fields, so two separate builds are equal
val twin: Lighthouse = Lighthouse("Portland", 41, 5)
val sameLight: Boolean = portland == twin
// match takes the value apart by position, binding each field to
// a name; a literal in one slot only matches that exact value
def describe(light: Lighthouse): String = light match
case Lighthouse(name, height, 5) => s"$name, ${height}m, quick"
case Lighthouse(name, _, secs) => s"$name every ${secs}s"
val summary: String = describe(portland)
Cómo funciona
case class Lighthousedeclara el registro y sus tres campos;Lighthouse("Portland", 41, 5)construye uno sin new.portland.toStringsale de los campos yportland == twincompara campo por campo: dos faros gemelos salen iguales.Lighthouse(name, height, 5)vincula por posición y exige ese literal en el tercero;(name, _, secs)cubre el resto.
Palabras clave y builtins usados aquí
caseclassdefmatchval
El intento, en números
- Líneas
- 20
- Caracteres a escribir
- 847
- Tokens
- 123
- Ritmo de tres estrellas
- 75 tpm
Al ritmo de tres estrellas de 75 tokens por minuto, este intento toma unos 98 segundos.
Paso 1 de 3 en Case classes y enums; paso 16 de 27 en Fundamentos del lenguaje.