Home > database >  String cannot be cast to Float - Kotlin
String cannot be cast to Float - Kotlin

Time:07-30

val nextDigit = passedList[i   1] as Float 

I'm trying cast this and It's giving that error. I tried with .toFloat() but It doesn't work..

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Float
    at com.example.calculator.MainActivity.calcTimesDiv(MainActivity.kt:108)

CodePudding user response:

as is a type casting operator. String and Float cannot be cast to each other. It is as simple as that. You will need to use extension functions like "toFloat()" that read the content of string and try to interpret is as a float value.

CodePudding user response:

Can you try this

val nextDigit = passedList[i   1]
nextDigit.toFloat()

CodePudding user response:

Try this,

val nextDigit = (passedList[i   1]).toFloat() 

PS: It is always good practice to wrap type cast inside try and catch block because Type casting may cause exception.

  • Related