In the following, I have a generic function fun <T : Number> sum(list : List<T>) : T
with a type parameter T : Number
.
In the function, I sum up the list's numbers as a sum : Double
and cast the sum in the end with return sum as T
.
For example, if a list of Int
is passed, I also get back an Int
- and this works.
fun <T : Number> sum(list : List<T>) : T {
var sum = 0.0
for(x in list)
sum += x.toDouble()
return sum as T
}
fun main() { println(sum(listOf(1,2,3))) } // prints 6
Yet, the following does not work, and I am wondering why the generic functions above works but directly casting a Double
to an Int
does not.
fun main() {
val d : Double = 6.0
val i = d as Int // java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
println(i)
}
I have to admit that I expected both cases to fail, but surprisingly, the generic function works and I don't know why.
So the question is: Why does the generic function work and does not throw a ClassCastException when casting from Double to Int?
6
! – Burgle