Kotlin is operator examples | Check variable is of an instance type
- Admin
- Mar 10, 2024
- Typescript
This tutorial explains how to check the variable type or instance of a class in Kotlin with examples.
Sometimes, developers need to check the runtime type of a class in Kotlin, and Kotlin provides the is
operator for this purpose.
What is the ‘is’ operator in Kotlin?
The is
operator is used to check if a given variable type is an instance of a specified class type. This is very helpful for developers to determine the type of an object at runtime.
is operator syntax
variable is class
Here, variable is a Kotlin valid variable declared with either a primitive
or custom class type
. Possible variable values include variables
, object variables, and strings.
fun main() {
val msg = "Cloudhadoop";
println(msg is String) // true
val num=123;
println(num is Int) // true
}
Kotlin Check class name as an string
Kotlin provides class literal syntax to get the name using reflection.
variable::class returns an class name
variable::class.java.typeName:
returns java class type namevariable::class.simpleName
: Returns just the class namevariable::class.qualifiedName
: It returns Kotlin Class Name.
Syntax:
variable::class.simpleName
variable::class.qualifiedName
variable::class.java.typeName
Here is an example
fun main() {
val msg = "Cloudhadoop";
println(msg::class.java.typeName)
println(msg::class.simpleName);
println(msg::class.qualifiedName);
val num=123;
println(num::class.java.typeName)
println(num::class.simpleName);
println(num::class.qualifiedName);
}
Output:
java.lang.String
String
kotlin.String
int
Int
kotlin.Int
Kotlin Check variable is of interface or class
The is operator checks whether a given variable implements an interface or is an instance of a class.
interface Animal {
fun eat()
}
class Lion : Animal {
override fun eat() {
}
}
fun main() {
val lion = Lion()
println(lion is Animal)
println(lion is Lion)
println(lion::class.java.typeName)
println(lion::class.simpleName);
println(lion::class.qualifiedName);
}
Output:
true
true
Lion
Lion
Lion
Conclusion
In conclusion, this tutorial provides a step-by-step example for checking the type of a variable or instance in Kotlin using the is
operator. It covers examples for primitive types, interfaces, and custom classes.