Cast String to Int

I am following the learnng programme.
All seems good however, sometime the online compiler seems to be playing games with me…

So, I m unable to get this String to Int cast to work.

fun main() {
val inp: String = “935”
val tenner: Int = (inp.subSequence(inp.length-2,inp.length)).toInt()

 println(tenner.toInt())

}

main()

This is failing…Plz help. I tried asing on SO but it is down currently…

returns a CharSequence which doesn’t define a .toInt() method.

substring however returns a string and your code works.

So just replace subSequence with substring and you’re good.

1 Like

Terminology nitpick: tenner.toInt() is a conversion. A cast would be tenner as Int.

The difference is that a conversion creates a new object of the required type (if needed), while a cast promises the compiler that the value is already of the required type (and will throw a ClassCastException if it’s not).

(I think the confusion arises because some languages, such as C, blur the distinction, using the same syntax for both. Even Java performs numeric conversions using its cast syntax. But Kotlin is much more explicit about these things — which prevents some types of bug. So it’s good to be clear about the difference.)