Possible Duplicate:
Using comparison operators in Scala’s pattern matching system
For below method I receive an error : "'=>' expected but integer literal found."
Is it not possible to check if x is greater than another number and or is there an alternative approach to return "greater than 2" if '> 2' is matched ?
def describe(x: Any) = x match {
case 5 => "five"
case > 2 => "greater than 2"
}
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.
Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.
Using if expressions in case statements First, another example of how to match ranges of numbers: i match { case a if 0 to 9 contains a => println("0-9 range: " + a) case b if 10 to 19 contains b => println("10-19 range: " + b) case c if 20 to 29 contains c => println("20-29 range: " + c) case _ => println("Hmmm...") }
It is defined in Scala's root class Any and therefore is available for all objects. The match method takes a number of cases as an argument. Each alternative takes a pattern and one or more expressions that will be performed if the pattern matches. A symbol => is used to separate the pattern from the expressions.
Try:
def describe(x: Any) = x match {
case 5 => "five"
case x: Int if (x > 2) => "greater than 2"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With