3

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

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

4 Comments

If you do this, then your custom implicit intToInteger can be deleted, because Scala does it for you.
almost, but no cigar: I get a different error, when I use this function definition and no implicit: "def mySum[T <% Number](as: T*): Double = as.foldLeft(0d)(_ + _.doubleValue)". The new error is: ambiguous implicit values: both method int2Integer in object Predef of type (x: Int)java.lang.Integer and method int2bigInt in object BigInt of type (i: Int)scala.math.BigInt match expected type Int => java.lang.Number
Are you importing scala.math.BigInt._? I was able to reproduce your error after doing that import. The error is occurring because BigInt contains its own implicit conversion that conforms to Int => Number, and the compiler doesn't know which one to use.
yes, removing the BigInt wildcard import fixes it. I just found this link (scala-lang.org/node/136) which states <: means subtype - the book im reading says subtype OR same type... thanks for the answer - ill accept it :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.