typestar

Métodos de extensión en Scala

Agregar métodos a Int y String sin ser dueño de ninguno de los dos tipos.

// An extension block adds methods to a type you do not own. Inside
// it, the named parameter stands for the receiver.
extension (n: Int)
  def isEven: Boolean = n % 2 == 0
  def clampTo(limit: Int): Int = if n > limit then limit else n

extension (s: String)
  def shout: String = s.toUpperCase + "!"
  def initials: String = s.split(' ').map(_.take(1)).mkString(".")

// The calls read as though Int and String had always had these.
val evens: List[Int] = (1 to 10).toList.filter(_.isEven)
val capped: Int = 137.clampTo(100)
val cheer: String = "ship it".shout
val short: String = "ada byron lovelace".initials

// A one-argument extension can also be written infix, without a dot.
val trimmed: List[Int] = List(3, 40, 500).map(_ clampTo 99)

Cómo funciona

  1. extension (n: Int) nombra el receptor y luego define isEven y clampTo sobre él.
  2. extension (s: String) agrega shout e initials igual.
  3. Las llamadas se leen como nativas, de 137.clampTo(100) al infijo _ clampTo 99.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
18
Caracteres a escribir
736
Tokens
152
Ritmo de tres estrellas
70 tpm

Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 130 segundos.

Escribe este fragmento

Paso 2 de 3 en Traits y extensiones; paso 23 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →