typestar

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

  1. ports.get(service) devuelve Some(port) o None en vez de lanzar.
  2. getOrElse(8080) cubre el caso ausente, y names.headOption es un head seguro sobre una lista vacía.
  3. isDefined responde sí o no, mientras el match además vincula el valor con case Some(port).

Palabras clave y builtins usados aquí

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.

Escribe este fragmento

Paso 1 de 3 en Option y Either; paso 19 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →

Option en otros lenguajes