Twitter LogoFacebook Logo
Type casting - smart cast and manual cast - is and as
Learn how casting works in Kotlin
By: King

Type Casting refers to the ability to temporarily "change" the type of a variable to something else as long as the Type is within the same category as the variable you are trying to cast.

is and !is Operators

In Kotlin, you can use the is and !is operators to check if a object is a specific type. This will automatically cast the object to the type it is checking, also known as Smart Cast.

Syntax for is

[variable] is [type]


fun castExample(x: Any) {

    if(x is String) {
        println("${x + 1}");
    } else if(x is Int) {
        println("${x + 1}");


In the example, there is a function call castExample that accepts a value of any type. 

Inside the function there are 2 if conditions that checks if the variable is a String or a Number. 

If a String is passed into the function, it will print the result of that String concatenated with the number 1. If a number is passed in, it will print the sum of x and 1.


This will print 1001 ("100" + 1) since x is casted to a String using the is operator. 


This will print 101 (100 + 1) since x is casted to a Int.

as Operator

Kotlin also provides ways to forcefully cast a type to an object using the "as" operator.

Syntax for as

[variable] as [type]


var str: String = "Welcome to"
var number: Int = str as Int

In the example, we are using the as operator to forcefully turn a String into a integer. However, this will throw an exception during runtime since a String cannot be turned into an Integer.

Unsafe and Safe Casts

Using the as operator forcefully cast an object to another type. This is also known as Unsafe casting. 

It is unsafe because using the operator will bypass the compiler's check for null and compatible values.

In the example, it casted a String into a Integer. Although there were no compiler error, the application will crash during runtime.

It will also crash if the value is null.

To turn the Unsafe cast to a safe one, we will need to use the Safe Cast operator "as?" (as with the ?).

var number = str as? Int

The as? operator will attempt to make the cast. If the cast operation fails, it will return null and no exception will be thrown. 

This way, you app will continue to operate.

Sign In