Reputation: 943
Currently I have:
val bar = "good"
val foo = bar match {
case "good" => "GREAT"
case _ => "BAD"
}
I would like to use another variable as a condition in case like this:
val x = 5
val bar = "good"
val foo = bar match {
case "good" and x = 5 => "GREAT"
case _ => "BAD"
}
Tried but didn't work:
val x = 5
val bar = "good"
val foo = bar match {
case y if (y == "good" && x == 5) => "GREAT"
case _ => "BAD"
}
Is something like this possible? Thanks.
Upvotes: 0
Views: 92
Reputation: 40500
What you wrote as "tried but didn't work", should actually work. Not sure what your problem was. Next time, please paste an actual error message rather than just saying "it didn't work".
You can also match against a tuple:
val x = 5
val bar = "good"
val foo = (bar, x) match {
case ("good", 5) => "GREAT"
case _ => "BAD"
}
Upvotes: 5
Reputation: 51271
You almost had it.
val foo = bar match {
case "good" if x == 5 => "GREAT"
case _ => "BAD"
}
Upvotes: 3