tkroman
tkroman

Reputation: 4798

How to pattern-match against every numeric class in one case?

Suppose I have

def foo(x: Any) = x match {
  case s: String => println(0)
  case i: Int => println(1)
  case l: Long => println(2)
  //...
}

Is there any way to make something like the following?

def foo(x: Any) = x match {
  case s: String => println(0)
  case i: Numeric => println("Numeric")
}

Upvotes: 10

Views: 4406

Answers (2)

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60006

You could try this:

def foo[A](x: A)(implicit num: Numeric[A] = null) = Option(num) match {
  case Some(num) => println("Numeric: " + x.getClass.getName)
  case None => println(0)
}

Then this

foo(1)
foo(2.0)
foo(BigDecimal(3))
foo('c')
foo("no")

will print

Numeric: java.lang.Integer
Numeric: java.lang.Double
Numeric: scala.math.BigDecimal
Numeric: java.lang.Character
0

Note that obtaining a null implicit parameter would not mean that no such implicit exist, but just that none was found at compile time in the search scope for implicits.

Upvotes: 6

Lee
Lee

Reputation: 144196

You could match against the Number interface:

def foo(x: Any) = x match {
  case s: String => println(0)
  case i: java.lang.Number => println("Numeric")
}

Upvotes: 7

Related Questions