6/30/2023 0 Comments Case scalaVersion 2 - leads to a compiler warningĪgain, compile the code with scalac, but right away you’ll see a warning message: Next, make a minor change to the code, replacing the integer literal 2 with a value: This shows that Scala was able to optimize your match expression to a tableswitch. The output from this command shows a tableswitch, like this: Next, disassemble that file with this javap command: First, place the following code in a file named SwitchDemo.scala:Ĭompiling this class produces no warnings and creates the output file SwitchDemo.class. The effect of the annotation is demonstrated with a simple example. If present, the compiler will verify that the match has been compiled to a tableswitch or lookupswitch, and issue an error if it instead compiles into a series of conditional expressions.” “An annotation to be applied to a match expression. Here’s the official description from the annotation documentation: When a value is given to the expression, it can jump directly to the result rather than working through the decision tree. This annotation provides a warning at compile time if the switch can’t be compiled to a tableswitch or lookupswitch.Ĭompiling your match expression to a tableswitch or lookupswitch is better for performance, because it results in a branch table rather than a decision tree. When writing simple match expressions like this, it’s recommended to use the annotation. A more functional approach returns a value from a match expression:Ĭase _ => "Invalid month" // the default, catch-all That example shows how to take an action based on a match. catch the default with a variable so you can print itĬase whoa => println("Unexpected case: " + whoa.toString) To use a Scala match expression like a Java switch statement, use this approach: You have a situation in your Scala code 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. This is Recipe 3.7, “How to use a Scala match expression like a switch statement.” Problem This is an excerpt from the 1st Edition of the Scala Cookbook (partially modified for the internet). show more info on classes/objects in repl.
0 Comments
Leave a Reply. |