Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: ClassCastException when casting double to integer?

Tags:

casting

kotlin

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?

like image 758
Slaknation Avatar asked Jan 26 '23 22:01

Slaknation


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
like image 148
Mahdi-Malv Avatar answered Jan 29 '23 12:01

Mahdi-Malv