4

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?

4
  • try toInt() function, e.g. (savedExercisesMap[exerciseKey] as HashMap<*, *>)["sets"].toInt() Commented Jan 5, 2019 at 18:15
  • @Sergey unresolved reference... Commented Jan 5, 2019 at 18:20
  • could you please provide entire code: savedExercisesMap, exerciseKey etc. Commented Jan 5, 2019 at 18:22
  • 3
    The exception message is quite clear: you're trying to cast a Double to an Integer. You can of course cast it to a Double, and then call toInt() on that Double to transform it to an Int, but really, this shows a big design issue in your code: if it's supposed to be an Int, why is it a Double? And most importantly, Kotlin being a type-safe language, why do you need so many casts to do what you want? Commented Jan 5, 2019 at 18:23

1 Answer 1

11

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
Sign up to request clarification or add additional context in comments.

Comments

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.