Kotlin: ClassCastException when casting double to integer?

Viewed 3554

I need to do a for loop in Kotlin:

for (setNum in 1..(savedExercisesMap[exerciseKey] as HashMap<*, *>)["sets"] as Int){

But I get this error:

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer

I wouldn't think this would be an issue. Is there a reason why this is happening and how to fix?

1 Answers

Casting from Double to Int will never succeed using as keyword. They both extend Number class and neither extends the other, so this cast is neither downcasting or upcasting. To convert a double to int in Kotlin you should use .toInt() function.

val aDouble: Double = 2.22222
//val anInt = aDouble as Int // wrong
val anInt = aDouble.toInt() // correct
Related