En este post te voy a explicar que son y como se usan los variable patterns en Scala.
¿Qué son las variable patterns en Scala?
Estos son una funcionalidad del lenguaje que permite extraer valores de un bloque match, asignarlos a una variable, y poder emplearlos en el cuerpo de la expresión «case».
Estas extracciones te pueden servir para incluirla como una condición en el «guard» o para transformar el argumento de entrada en otra cosa.
Ejemplo.
En el siguiente ejemplo utilice el variable pattern para extraer valores de una case class, una option y una tupla. La funcionalidad es la misma en los tres casos. Lo única que cambia es el objeto base que requiere el bloque match.
case class Vegetable(private val weight:Double, private val name:String) { | |
def getName: String = name | |
def getWeight: Double = weight | |
} | |
var cucumber = new Vegetable(0.5, "Cucumber") | |
var lettuce = new Vegetable(2, "Lettuce") | |
var tomato = new Vegetable(3.5, "Tomato") | |
//Example of variable pattern with apply and unapply | |
def processVegetables(input:Vegetable) = { | |
input match { | |
case Vegetable(weight, _) if weight < 1 => println(s"Weight: $weight lbs") | |
case Vegetable(_, name) if name == "Tomato" => println(s"This is a Tomato") | |
case Vegetable(weight,name) => println(s"This is a $name, weight: $weight ") | |
} | |
} | |
processVegetables(cucumber) | |
processVegetables(lettuce) | |
processVegetables(tomato) | |
//Example with variable pattern with Option, Some and None. | |
def processVegetablesWithOption(option: Option[Vegetable]) = { | |
option match { | |
case Some(v) if v.getWeight < 1 => println(s"Weight: ${v.getWeight} lbs") | |
case Some(v) if v.getName == "Tomato" => println(s"This is a Tomato") | |
case Some(v) => println(s"This is a ${v.getName}, weight: ${v.getWeight} ") | |
case None => println("None") | |
} | |
} | |
processVegetablesWithOption(Some(cucumber)) | |
processVegetablesWithOption(Some(lettuce)) | |
processVegetablesWithOption(Some(tomato)) | |
processVegetablesWithOption(None) | |
//Example of variable pattern with tuples. | |
def processVegetablesWithTuples(tuple: (Double, String)) = { | |
tuple match { | |
case (weight, _) if weight < 1 => println(s"Weight: $weight lbs") | |
case (_, name) if name == "Tomato" => println(s"This is a Tomato") | |
case (weight, name) => println(s"This is a $name, weight: $weight ") | |
} | |
} | |
implicit def ToTuple(input:Vegetable): (Double, String) = (input.getWeight, input.getName) | |
processVegetablesWithTuples(cucumber) | |
processVegetablesWithTuples(lettuce) | |
processVegetablesWithTuples(tomato) |
- NVL in SQL Server - 2023-11-01
- ¿Que es Cake Build? - 2023-02-22
- #How to fix error: MSB4019: The imported project «Microsoft.Data.Tools.Schema.SqlTasks.targets» was not found - 2023-02-20