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

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.


The empty default case is necessary in your pattern matching example, because otherwise the match expression would throw a MatchError for every expr argument that is not a bar.

The fact that no code is specified for that second case, so if that case runs it does nothing.

The result of either case is the Unit value (), which is also, therefore, the result of the entire match expression.

More details on it in Martin Odersky's Programming in Scala book under Case Classes and Pattern Matching chapter.

Tags:

Syntax

Scala