typestar

Argumentos por defecto y con nombre en Scala

Parámetros con valores por defecto, y llamadas que nombran sus argumentos en vez de ordenarlos.

// A parameter with a default may be left out by the caller.
def ticketLine(film: String, seats: Int = 1, matinee: Boolean = false) =
  val each = if matinee then 8.5 else 12.0
  f"$film%-12s $seats seat(s) ${each * seats}%6.2f"

// A default is evaluated only when the argument is left out.
def refund(paid: Double, fee: Double = 1.5): Double = paid - fee

def boxOffice(): Unit =
  // Omitted parameters fall back to their defaults.
  println(ticketLine("Nosferatu"))
  // Named arguments may be written in any order.
  println(ticketLine(seats = 3, film = "Solaris"))
  // Positional first, then named to skip a middle parameter.
  println(ticketLine("Stalker", matinee = true))
  println(refund(24.0))
  println(refund(24.0, fee = 0.0))

Cómo funciona

  1. def ticketLine(film: String, seats: Int = 1, matinee: Boolean = false) da valor por defecto a dos de tres parámetros.
  2. ticketLine("Nosferatu") usa los dos por defecto; seats = 3, film = "Solaris" nombra y reordena sus argumentos.
  3. ticketLine("Stalker", matinee = true) pasa uno por posición y nombra el último para saltarse seats.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
17
Caracteres a escribir
720
Tokens
123
Ritmo de tres estrellas
75 tpm

Al ritmo de tres estrellas de 75 tokens por minuto, este intento toma unos 98 segundos.

Escribe este fragmento

Paso 2 de 3 en Funciones; paso 8 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →