2017-07-07 113 views
2

我想如果我尝试使用这样这个函数来执行此功能澄清斯卡拉功能

def sumofdouble[T <:Number] (as:T*): Double = as.foldLeft(0d)(_ + _.doubleValue) 

的,

sumofdouble(1,2) 

我收到此错误

<console>:13: error: inferred type arguments [Int] do not conform to method sumofdouble's type parameter bounds [T <: Number] 
sumofdouble(1,2) 

难道不是'整数是一个数字的子类型?请解释我是否缺少一些东西。

回答

5

看起来你正在使用java.lang.Number。不幸的是,scala中的数值类型不能从这个类继承(参考看Int定义 - 就像它直接从AnyVal - http://www.scala-lang.org/api/2.12.0/scala/Int.html继承的其他scala的数字) - 它根本不在它们的层次结构中。你想要使用的是隐含的Numeric类型类来转换你的数字。

def foo[T](as: T*)(implicit n: Numeric[T]) = as.foldLeft(0d)(_ + n.toDouble(_))

看到这个问题的进一步的信息 - Scala equivalent of Java's Number