Is Operator (is and !is) in Kotlin
On this page (8sections)
Definition
- Is operators are used to check if a variable is of a particular type or not(!is) in Kotlin.
- This operator is mainly used in when and if statements.
- This operator is equivalent to the “instanceOf” method in Java.
Syntax
1. is Operator
if(value is variable_type){
//Block of Code
}
For example,
if(value is String){
println("$value is a String")
}
2. !is Operator
if(value !is variable_type){
//Block of Code
}
For example,
if(value !is String){
println("$value is not a String")
}
Is and !is Operator Example Program in Kotlin
//Is Operator Example Program in Kotlin
//Operator Kotlin Programs, Basic Kotlin Program
fun main(args: Array<String>) {
val name = "Little Drops"
val number = 5
println("Checking data type of : $name")
checkDataType(name)
println()
println("Checking data type of : $number")
checkDataType(number)
}
fun checkDataType(value : Any){
if(value is String){
println("$value is a String")
}
if(value !is String){
println("$value is not a String")
}
if(value is Int){
println("$value is an Int")
}
if(value !is Int){
println("$value is not an Int")
}
}
Sample Output
Checking data type of : Little Drops
Little Drops is a String
Little Drops is not an Int
Checking data type of : 5
5 is not a String
5 is an Int
How It Works
This Kotlin program demonstrates Is Operator (is and !is). It first prepares the data it needs, then uses conditional logic to decide the result, and finally prints the output shown in the Sample Output above.
- Declare the variables that hold the program’s data.
- Use conditional statements to handle the different cases.
- Print the final result to the console so you can compare it with the sample output.
Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.
Frequently Asked Questions
What is Is Operator (is and !is) in Kotlin?
Is operators are used to check if a variable is of a particular type or not(!is) in Kotlin.
How do I run this Kotlin example?
Run it in IntelliJ IDEA or Android Studio, or compile from the command line with `kotlinc file.kt -include-runtime -d file.jar` and run `java -jar file.jar`.
How can I practice Is Operator (is and !is)?
Copy the example into IntelliJ IDEA or Android Studio, run it, then change the values or add print statements to see how the output changes.