Friday, November 12, 2010

Scala Switch...I mean Match Case

The syntax here is different than Java and the trickiest part was finding out that the default (fall back) case is defined by the underscore character:
 
def matchTest(x: Int): String = x match {
case LIGHT => "LL "
case LIGHT_KING => "LK "
case DARK => "DD "
case DARK_KING => "DK "
case _ => "-- "
}

In Scala, you define the match case as a method with a return value. If you want to execute the match case, you simply create a var and say: var = matchTest(integerValue).

This will evaluate the match case and either assign a matched value OR fall back on the default case _.

No comments:

Post a Comment