Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use switch/case (simple pattern matching) in Scala?

I've found myself stuck on a very trivial thing :-]

I've got an enum:

 object Eny extends Enumeration {       type Eny = Value       val FOO, BAR, WOOZLE, DOOZLE = Value     } 

In a code I have to convert it conditionally to a number (varianr-number correspondence differs on context). I write:

val en = BAR val num = en match {   case FOO => 4   case BAR => 5   case WOOZLE => 6   case DOOZLE => 7 } 

And this gives me an "unreachable code" compiler error for every branch but whatever is the first ("case FOO => 4" in this case). What am I doing wrong?

like image 710
Ivan Avatar asked Sep 03 '10 19:09

Ivan


People also ask

How do you match a pattern in Scala?

A pattern match includes a sequence of alternatives, each starting with the keyword case. Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches. An arrow symbol => separates the pattern from the expressions.

Does Scala have pattern matching?

Notes. Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.

How is case class used in pattern matching?

Case classes help us use the power of inheritance to perform pattern matching. The case classes extend a common abstract class. The match expression then evaluates a reference of the abstract class against each pattern expressed by each case class.


2 Answers

The following code works fine for me: it produces 6

object Eny extends Enumeration {   type Eny = Value   val FOO, BAR, WOOZLE, DOOZLE = Value }  import Eny._  class EnumTest {     def doit(en: Eny) = {         val num = en match {           case FOO => 4           case BAR => 5           case WOOZLE => 6           case DOOZLE => 7         }                 num     } }  object EnumTest {     def main(args: Array[String]) = {         println("" + new EnumTest().doit(WOOZLE))     } } 

Could you say how this differs from your problem please?

like image 20
Matthew Farwell Avatar answered Oct 12 '22 23:10

Matthew Farwell


I suspect the code you are actually using is not FOO, but foo, lowercase, which will cause Scala to just assign the value to foo, instead of comparing the value to it.

In other words:

x match {   case A => // compare x to A, because of the uppercase   case b => // assign x to b   case `b` => // compare x to b, because of the backtick } 
like image 116
Daniel C. Sobral Avatar answered Oct 12 '22 22:10

Daniel C. Sobral