Kotlin Type Checking, Kotlin Type Casting With Examples

Today we will look into Kotlin type checking and smart type casting. We will use Kotlin Online playground for code snippets.

Kotlin Type Checking

Type Checking is the way to check the type of a data at runtime. In Java, we have the instanceof keyword to check the type. Kotlin uses is and !is keywords to check whether a property is and is not of a certain type respectively.

Let’s look at an example code for the same.

The first if-else expression would print type is String. The second would give a compilation error since Kotlin is powerful enough to determine the types at compile time itself.

Let’s create a list of Any objects and check the type of each element.

We’ll use the when statement to check the type of each element in a for loop.

Following is the output of the above code.


Kotlin Smart Type Casting

Smart type casting is one of the most interesting features available in Kotlin. It automatically casts a property to the desired type on the right hand side if the condition meets.

In the above code, we don’t need to unwrap the optional. If the smart cast passes the above null checker, optional is unwrapped automatically.

The output printed from the above piece of code is given below.

Kotlin Type Checking, Kotlin Type Casting With Examples

The same equivalent code in Java would look like this:

In the above code, we’re first checking the instanceOf and then explicitly type casting. Kotlin makes it way simpler thanks to Smart Casting.

Smart Casting With Binary Operators

Smart Casting is also possible with binary operators as shown in the below code.

In the above code, in the first function, if the first condition is true, Kotlin type casts the parameter in the second parameter to the same type.

Smart Casts in Classes

Let’s create classes that implement an interface as shown below:

The Random function gets a random integer between 0 to 10. Based on whether it’s even or odd, the interface creates instantiates from either of the classes.

The is operator then calls the method in the if expressions by smart casting the type of the class.

Note: The Kotlin compiler does not smart cast when it cannot guarantee that the value hasn’t changed between check and usage. It always smart casts for val properties and can never do so for var properties.

Explicit Type Casting

We can explicitly type cast properties in Kotlin using the as operator.

The as operator is unsafe. It can lead to ClassCastException similar to Java in scenarios shown below.

x is not a nullable type, so it cannot be set to null. For this case, we’ll can do either of the following:

This allows us to set x as a null.

But the above approach would fail when:

So we need to use the as? operator which instead of giving a runtime exception, sets a null value if the cast doesn’t succeed.

That’s all for type checking and smart casting in kotlin programming language.

By admin

Leave a Reply

%d bloggers like this: