2017-07-07 184 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