我正在尝试执行此功能
def sumofdouble[T <:Number] (as:T*): Double = as.foldLeft(0d)(_ + _.doubleValue)
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用这样的功能,
sumofdouble(1,2)
Run Code Online (Sandbox Code Playgroud)
我收到了这个错误
<console>:13: error: inferred type arguments [Int] do not conform to method sumofdouble's type parameter bounds [T <: Number]
sumofdouble(1,2)
Run Code Online (Sandbox Code Playgroud)
整数不是Number的子类型吗?请解释我是否遗漏了一些东西.
看起来你正在使用java.lang.Number.可惜的是,数值类型Scala中不从这个类(供参考看看继承Int定义-像其他Scala的NUMERICS它直接继承AnyVal- http://www.scala-lang.org/api/2.12.0/scala/Int. html) - 它根本不在他们的层次结构中.您想要使用的是Numeric用于转换数字的隐式类型.
def foo[T](as: T*)(implicit n: Numeric[T]) = as.foldLeft(0d)(_ + n.toDouble(_))
有关更多信息,请参阅此问题 - Scala等效于Java的数字.
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |