10

假设我有

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

有什么方法可以制作如下内容吗?

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

2 回答 2

6

您可以匹配Number界面:

def foo(x: Any) = x match {
  case s: String => println(0)
  case i: java.lang.Number => println("Numeric")
}
于 2013-11-03T19:43:10.983 回答
5

你可以试试这个:

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

那么这个

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

将打印

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

请注意,获得null隐式参数并不意味着不存在这样的隐式参数,而只是在编译时在隐式搜索范围内没有找到任何隐式参数。

于 2013-11-03T19:43:29.537 回答