Pattern matching
Using variables in pattern matching
val val1: String = "MyVal1"
val val2: String = "MyVal2"
val val3: String = "MyVal3"
def matchInput(input: String): String = input match {
case `val1` => "Matched val1"
case `val2` => "Matched val2"
case `val3` => "Matched val3"
case _ => "Didn't match any known val"
}
println(matchInput("MyVal1")) //prints: Matched val1
println(matchInput("MyVal2")) //prints: Matched val2
println(matchInput("MyVal3")) //prints: Matched val3
println(matchInput("MyVal4")) //prints: Didn't match any known val
In the matchInput method, the value of the input
variable is compared to the values of the vals
, initiated above.