Reputation: 2100
I am trying to execute this function
def sumofdouble[T <:Number] (as:T*): Double = as.foldLeft(0d)(_ + _.doubleValue)
If I try using this function like this,
sumofdouble(1,2)
I am getting this error
<console>:13: error: inferred type arguments [Int] do not conform to method sumofdouble's type parameter bounds [T <: Number]
sumofdouble(1,2)
Isn't Integer a subtype of Number? Please explain if I am missing something.
Upvotes: 2
Views: 82
Reputation: 8427
Looks like you are using java.lang.Number
. Unfortunatelly, numeric types in scala do not inherit from this class (for reference look at Int
definition - like other scala's numerics it inherits directly from AnyVal
- http://www.scala-lang.org/api/2.12.0/scala/Int.html) - it is simply not in their hierarchy. What you want to use is the implicit Numeric
type class to convert your numbers.
def foo[T](as: T*)(implicit n: Numeric[T]) = as.foldLeft(0d)(_ + n.toDouble(_))
See this question for further information - Scala equivalent of Java's Number.
Upvotes: 5