How to turn Any into Int in Kotlin

I have an attribute in my model described above, which in some cases contains Int.

var value: Any?

I know that I can do this if I pass String first and then Int

value.toString().toInt() // works

Is there a way to do this by skipping casting to a string? When I try to do it directly in Int, I get this error

FATAL EXCEPTION: main
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
+7
source share
2 answers

The problem is that you tried to do a direct from String to Int using value as Int.

, , , value , Int. , String , , Int. toInt().

, , , toInt() String, value Any?. , toInt() value, , , , . , , :

if (value is String) {
    value.toInt()
}

Kotlin: https://kotlinlang.org/docs/reference/typecasts.html#smart-casts

. , Int, , , , , String, . , , Int String? , , , , Any?. / , .

+11

Kotlin Safe Cast as? Int. :

fun giveAny(): Any {
    return "12"
}

fun giveInt(): Int {
    return giveAny() as Int  // here we are casting giveAny() return to Int
}

fun giveNullableInt(): Int? {
    return giveAny() as? Int  // here we are casting giveAny() return to nullable Int
}
0

Source: https://habr.com/ru/post/1017113/


All Articles