Let's see how to type check an object in these steps:
- Let's try a very basic example, trying is with string and integer. In this example, we will type check a string and an integer:
fun main(args: Array<String>) {
var a : Any = 1
var b : Any = "1"
if (a is String) {
println("a = $a is String")
}
else {
println("a = $a is not String")
}
if (b is String) {
println("b = $b is String")
}
else {
println("b = $b is not String")
}
}
- Similarly, we can use !is to check whether the object is not of type String, like this:
fun main(args: Array<String>) {
var b : Any = 1
if (b !is String) {
println("$b is not String")
}
else {
println("$b is String")
}
}
If you remember how when works in Kotlin, we do not need to put in the is keyword, because Kotlin has a feature of smart cast and throws an error if the compared objects are not of the same type.