Type checking with the is keyword

Type inference is one of the most powerful features in Kotlin, but sometimes it becomes hazardous when the type of variable is unknown. For example, we are asked to write a function that can take variable of the Any type. This can be float, string, or int:

fun func(x: Any) { 
// What is the type of x
}

To handle this tricky situation, Kotlin provides an is keyword to verify the variable type. The syntax for this is as follows:

x is Int
x is Char

This check will return true if x is an integer or character; otherwise, it will return false. Check the following examples:

fun func(x: Any) { 
if(x is Float){
println("x is Float")
} else if(x is String){
println("x is String")
}

!is can be used to verify whether or not a variable is a required type:

fun func(x: Any) { 
if(x !is Float){
println("f is not Float")
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.19.174