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

How does the compiler interpret this ?:

foo match { case bar: Bar => println("First case statement") case _ => } 

The second case is left blank and nothing is returned.

+11
source share
3 answers

This 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 a bar" case _ => } 

Now the compiler has drawn Any , because this is the first common supertype between String and Unit .

Please note that the match in your case is incorrect, because only matching with bar means "catch all variables", maybe you wanted bar: Bar .

+15
source

In the pattern matching example, an empty case is required by default , because otherwise the match expression will raise a MatchError for each expr argument that is not a bar.

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

The result of any of these is the value of Unit () , which is also the result of the entire expression of correspondence.

For more information, see Martin Odersky Programming with Scala in Class Classes and Pattern Matching.

+1
source

An empty default case is required in your pattern matching example, because otherwise, a match expression will throw a MatchError for every expr argument that is not a bar.

So, perhaps, in the current version of scala this rule does not work, it really shows that the constructor cannot be created for the expected type

0
source

Source: https://habr.com/ru/post/975282/


All Articles