Átomo
6Pm
Fundamentos · Scala

pattern matching

Abrir na tabela

Definição

match compara um valor com padrões: constantes, tipos, case classes e condições.

Exemplos

1. Constantes
val mode = args(1) match {
  case "full"  => "overwrite"
  case "delta" => "append"
  case other   => throw new IllegalArgumentException(s"unknown mode: $other")
}
2. Case class e condição
sale match {
  case Sale(_, _, amount, _) if amount > 1000 => "HIGH"
  case Sale(_, _, amount, _) if amount > 100  => "MEDIUM"
  case _                                      => "LOW"
}
3. Por tipo
value match {
  case n: Int    => s"int $n"
  case s: String => s"string $s"
  case _         => "other"
}

No mesmo grupo