Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to have an 'empty' case statement in Scala?

Tags:

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.

like image 610
Core_Dumped Avatar asked Sep 15 '14 08:09

Core_Dumped


People also ask

What is case statement in Scala?

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 {

What is Scala match case?

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.

How do you write a switch statement Scala?

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.

How do you use match function in Scala?

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...") }


1 Answers

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.

like image 182
Ende Neu Avatar answered Sep 22 '22 06:09

Ende Neu