I've tried code as below
val a: Int? = 1024
println(a is Int) // true
println(a is Int?) // true
println(a is String) // **error: incompatible types: Long and Int? why the value cannot be checked with any type?**
but this works well:
fun checkType(x: Any?) {
when(x) {
is Int -> ...
is String -> ... // **It works well here**
else -> ...
}
}
It works this way:
fun main(args: Array<String>) {
val a = 123 as Any? //or val a: Any = 123
println(a is Int) // true
println(a is Int?) // true
println(a is String) //false
checkType(a) //Int
}
fun checkType(x: Any?) {
when(x) {
is Int -> println("Int")
is String -> println("String")
else -> println("other")
}
}
It's because val a: Int?
is definetely not one of String
type, compilator knows it and doesn't allow you to run a is String
.
You should use more abstract type to define your variable.
You don't need to create a separate function to check its type. You can simply cast to Any?
type:
println(a as Any? is String)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With