Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching in scala, check if number greater than [duplicate]

Tags:

scala

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"
  }
like image 283
user701254 Avatar asked Oct 23 '12 19:10

user701254


People also ask

Does Scala have pattern matching?

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.

How does Scala pattern matching work?

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.

What are the different ways to implement match expressions in scala?

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...") }

What is case class and pattern matching in Scala?

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.


1 Answers

Try:

def describe(x: Any) = x match {
  case 5 => "five"
  case x: Int if (x > 2) => "greater than 2"
}
like image 75
Matthew Farwell Avatar answered Sep 22 '22 01:09

Matthew Farwell