Kotlin is
Kotlin is
Operator is used to check if a an object conforms to a given type.
The syntax to use is
operator is
<object> is <Type>
where object
is the Kotlin object whose type we would like to check, and Type
is the class.
Return Value
is
Operator returns a boolean value. It returns true
if the object conforms to the given type, or false
if not.
Examples for Kotlin ‘is’ operator
In the following program, we will initialize a variable with String, and check programmatically if this variable is of type String, using is
operator.
Main.kt
fun main(args: Array<String>) {
var str: Any = "Hello World!"
val result = str is String
println("Is str object a String? " + result)
}
Output
Is str object a String? true
We can use this expression with is
operator as a condition for Kotlin If statement.
Main.kt
fun main(args: Array<String>) {
var str: Any = "Hello World!"
if (str is String) {
println("str object is a String.")
} else {
println("str object is not a String.")
}
}
Output
str object is a String.
We can also use NOT Operator ! with is as shown in the following program.
Main.kt
fun main(args: Array<String>) {
var str:Any = 25
if (str !is String) {
println("str object is not a String.")
} else {
println("str object is a String.")
}
}
Output
str object is not a String.
Error – Kotlin: Incompatible types
If the type of object is specified or derived implicitly by the value assigned to it, and if this type is not compatible with the type we are checking against, Kotlin would throw the following error.
Kotlin: Incompatible types: String and Int
Let us recreate the above said scenario. We have initialized a variable x
with integer value. Also, no explicit type is specified for x
. Therefore the type of x
is Int
. And in the line 3, we are checking if x
is String
. Since, Int
and String
are incompatible types, Kotlin would throw an error.
Main.kt
fun main(args: Array<String>) {
var x = 25
val result = x is String
println("Is x object a String? " + result)
}
Output
str object is not a String.
To solve this, specify the type of x
as Any
, which we did in our previous examples.
Main.kt
fun main(args: Array<String>) {
var x: Any = 25
val result = x is String
println("Is x object a String? " + result)
}
Output
Is x object a String? false
Conclusion
In this Kotlin Tutorial, we learned about Kotlin is Operator, and how to use it to check an object conforms to a given type, with the help of examples.