skip to Main Content
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)

3

Answers


  1. 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.

    Login or Signup to reply.
  2. Can you try this

    val nextDigit = passedList[i + 1]
    nextDigit.toFloat()
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search