August 2013
Intermediate to advanced
720 pages
16h 23m
English
You have a situation where you want to create something like a
simple Java integer-based switch
statement, such as matching the days in a week, months in a year, and
other situations where an integer maps to a result.
To use a Scala match expression like a Java switch statement, use this approach:
// i is an integerimatch{case1=>println("January")case2=>println("February")case3=>println("March")case4=>println("April")case5=>println("May")case6=>println("June")case7=>println("July")case8=>println("August")case9=>println("September")case10=>println("October")case11=>println("November")case12=>println("December")// catch the default with a variable so you can print itcasewhoa=>println("Unexpected case: "+whoa.toString)}
That example shows how to take an action based on a match. A more functional approach returns a value from a match expression:
valmonth=imatch{case1=>"January"case2=>"February"case3=>"March"case4=>"April"case5=>"May"case6=>"June"case7=>"July"case8=>"August"case9=>"September"case10=>"October"case11=>"November"case12=>"December"case_=>"Invalid month"// the default, catch-all}
When writing simple match expressions like this, it’s recommend
to use the @switch annotation. This
annotation provides a warning at compile time if the switch can’t be
compiled to a tableswitch ...
Read now
Unlock full access