However, for many situations, your code will be simpler and easier to read by joining the if guard directly with the case statement.Apr. If (name = "Fred") println("Yubba dubba doo")Įlse if (name = "Bam Bam") println("Bam bam!") Note that all of these examples could be written by putting the if tests on the right side of the expressions, like this: You can use this syntax whenever you want to add simple matches to your case statements on the left side of the expression. ![]() You can also extract fields from case classes and use those in your guards:Ĭase Person(name) if name = "Fred" => println("Yubba dubba doo")Ĭase Person(name) if name = "Bam Bam" => println("Bam bam!")Ĭase _ => println("Watch the Flintstones!") Imagine here that x is an instance of a Stock class that has symbol and price fields:Ĭase x if (x.symbol = "XYZ" & x.price buy(x)Ĭase x if (x.symbol = "XYZ" & x.price > 50) => sell(x) You can reference class fields in your if guards. Use it to match different values of an object:Ĭase x if x = 1 => println("one, a lonely number")Ĭase x if (x = 2 || x = 3) => println(x) Use it to match a range of numbers:Ĭase a if 0 to 9 contains a => println("0-9 range: " + a)Ĭase b if 10 to 19 contains b => println("10-19 range: " + b)Ĭase c if 20 to 29 contains c => println("20-29 range: " + c) ![]() SolutionĪdd an if guard to your case statement. You want to add qualifying logic to a case statement in a Scala match expression, such as allowing a range of numbers, or matching a pattern, but only if that pattern matches some additional criteria. This is Recipe 3.13, “How to add if expressions (guards) to match/case expressions.” 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. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |