Ant Kutschera
Ant Kutschera

Reputation: 6588

Implicit function in Scala not working as expected

If I define the following function which expects a Long, and I define the following implicit function, the implicit function is used when I pass a Date to the first function and everything works as expected:

def millisToDays(in: Long): Int = (in / (1000L * 3600L * 24L)).toInt
implicit def dateToLong(d: Date) = d.getTime
println(millisToDays(new Date))

But for the following second example, I get a compiler error on the third line: "inferred type arguments [Int] do not conform to method mySum's type parameter bounds [t <: java.lang.Number]"

def mySum[T <: Number](as: T*): Double = as.foldLeft(0d)(_ + _.doubleValue)
implicit def intToInteger(n: Int): Integer = new Integer(n.toInt)
var r = mySum(2, 3)

What have I done wrong? Why isn't the intToInteger implicit function being used?

I am guessing that the problem is that the implicit function does not return a "T <: Number", but rather an Integer, so the compiler can't guess that the implicit function is actually useful.

Is there anyway which I can give the compiler a hint that it should use the implicit function?

Thanks! Ant

Upvotes: 3

Views: 607

Answers (1)

Dan Simon
Dan Simon

Reputation: 13137

The [T <: Number] type bounds means that T must be a subtype of Number. The implicit conversion from Int to Integer doesn't give you this, since even though the conversion is available it still doesn't mean that Int is a subtype of Number.

Luckily, there is something similar called view bounds, written [T <% Number], which specifies exactly what you want, that there is an implicit conversion available from T to Number

Upvotes: 5

Related Questions