繁体   English   中英

如何在一种情况下对每个数字类进行模式匹配?

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

假设我有

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

您可以匹配Number接口:

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

你可以试试这个:

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隐式参数并不意味着不存在这样的隐式参数,而只是在编译时在搜索范围内找不到任何隐含参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM