Kotlin is operator examples | Check variable is of an instance type

This tutorials explains about how to check variable type or instance of an class in Kotlin with example

Sometimes, We want to check runtime type of an class in Kotlin with examples. Kotlin provides is operator to check an instance of an class.

What is is operator in Kotlin?

is operator used to check if given variable type is an instance of a given class type or not. This will very helpful for developers to know the type of the object at runtime.

is operator syntax

variable is class

variable is an Kotlin valid variables declared with either Primitive or Custom Class.

possible variables values are 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 name using reflection. variable::class returns an

variable::class.java.typeName: returns java class type name

variable::class.simpleName: It just returns class name variable::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

is operator checks an give variable implements an interface or check an instance of an class using is Operator

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

To sum up, Learned A Step by Step example for Kotlin checks type of or instance of operator in Kotlin with examples for primitive and interfaces and custom classes