How does the compiler interpret this?:
foo match {
case bar: Bar => println("First case statement")
case _ =>
}
The second case is left empty, with nothing to return.
At the most basic level, Scala's Match Case is just like a switch statement in Java or C++. So, like any other language, the Match Case allows you to select among multiple alternatives. Here is an example. def matchX(x: Int) = { x match {
It is similar to the switch statement of Java and C. Here, “match” keyword is used instead of switch statement. “match” is always defined in Scala's root class to make its availability to the all objects. This can contain a sequence of alternatives. Each alternative will start from case keyword.
We can apply the @switch annotation to a match statement in Scala. We can use the @switch annotation to make sure that the compiler applies the optimization to our pattern match expression. The compiler emits a warning message if it's not able to do any optimization.
Using if expressions in case statements First, another example of how to match ranges of numbers: i match { case a if 0 to 9 contains a => println("0-9 range: " + a) case b if 10 to 19 contains b => println("10-19 range: " + b) case c if 20 to 29 contains c => println("20-29 range: " + c) case _ => println("Hmmm...") }
It means return Unit
:
val res: Unit = new foo match {
case bar: Bar => println("First case statement")
case _ =>
}
If you change your statement to return something instead of println
(which returns Unit
):
val res: Any = new foo match {
case bar: Bar => "it's a bar"
case _ =>
}
Now the compiler has inferred Any
because it's the first common supertype between String
and Unit
.
Note that your case match is wrong because matching on bar
alone means catch all the variables, you probably wanted bar: Bar
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With