Option en Scala
La respuesta de Scala a null: un valor que está o admite que no está.
// Option is the type for "maybe a value", used where null would be.
val ports: Map[String, Int] = Map("http" -> 80, "ssh" -> 22)
// Map.get never throws: it answers Some(value) or None. getOrElse
// then covers the None case and hands back a plain Int.
def portOrDefault(service: String): Int = ports.get(service).getOrElse(8080)
// headOption is a safe head, returning None for an empty list.
def firstService(names: List[String]): Option[String] = names.headOption
// isDefined answers yes or no, and never reaches the value itself.
def isKnown(service: String): Boolean = ports.get(service).isDefined
// A match asks the same question but also binds what is inside.
def describe(service: String): String = ports.get(service) match
case Some(port) => s"$service listens on $port"
case None => s"$service is not configured"
Cómo funciona
ports.get(service)devuelveSome(port)oNoneen vez de lanzar.getOrElse(8080)cubre el caso ausente, ynames.headOptiones un head seguro sobre una lista vacía.isDefinedresponde sí o no, mientras elmatchademás vincula el valor concase Some(port).
Palabras clave y builtins usados aquí
casedefmatchval
El intento, en números
- Líneas
- 17
- Caracteres a escribir
- 835
- Tokens
- 122
- Ritmo de tres estrellas
- 70 tpm
Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 105 segundos.
Paso 1 de 3 en Option y Either; paso 19 de 27 en Fundamentos del lenguaje.