Kotlin Type Checks and Smart Casts: is, as and as?

Kotlin course · Advanced Kotlin · Lesson 45 of 51

Updated:

Sometimes a variable can hold values of different types, for example a parameter of type Any, or a sealed type with several subclasses. Kotlin lets you check the type with is, and then automatically casts the value for you. That’s called a smart cast.

Checking a type with is and !is

fun main() {
    val items: List<Any> = listOf(42, "Kotlin", 3.14, true)
    for (x in items) {
        println("$x is String? ${x is String}   is not Int? ${x !is Int}")
    }
}

Output:

42 is String? false   is not Int? false
Kotlin is String? true   is not Int? true
3.14 is String? false   is not Int? true
true is String? false   is not Int? true

Smart casts

After an is check, you can use the value as that type without converting it yourself:

fun describe(x: Any): String {
    if (x is String) {
        return "Text of length ${x.length}"     // x is a String here
    }
    if (x is Int && x > 10) {                    // smart cast works in && too
        return "Big number: ${x * 2}"
    }
    return "Something else: $x"
}

fun main() {
    println(describe("Hello"))
    println(describe(21))
    println(describe(3))
}

Output:

Text of length 5
Big number: 42
Something else: 3

It also works after a negative check that returns early:

fun shout(x: Any): String {
    if (x !is String) return "Not text"
    return x.uppercase() + "!"     // from here on, x is a String
}

fun main() {
    println(shout("kotlin"))
    println(shout(5))
}

Output:

KOTLIN!
Not text

Smart casts with when

when with is branches is the most common way to handle several types:

fun area(shape: Any): Double = when (shape) {
    is Double -> shape * shape                 // a square's side
    is Pair<*, *> -> (shape.first as Double) * (shape.second as Double)
    is String -> shape.toDoubleOrNull() ?: 0.0
    else -> 0.0
}

fun main() {
    println(area(3.0))
    println(area(2.0 to 5.0))
    println(area("12.5"))
}

Output:

9.0
10.0
12.5

With a sealed class, as in the sealed classes lesson, the compiler also knows when you’ve covered every type.

Null checks are smart casts too

fun printLength(text: String?) {
    if (text != null) {
        println(text.length)       // String? became String
    } else {
        println("No text")
    }
}

fun main() {
    printLength("Kotlin")
    printLength(null)
}

Output:

6
No text

Explicit casts: as and as?

OperatorIf the type is wrong
x as Stringthrows ClassCastException
x as? Stringreturns null
fun main() {
    val value: Any = "123"

    val s = value as String
    println(s.length)

    val n: Int? = value as? Int
    println(n)

    try {
        val bad = value as Int
        println(bad)
    } catch (e: ClassCastException) {
        println("Can't cast a String to Int")
    }
}

Output:

3
null
Can't cast a String to Int

Prefer is with a smart cast, or as? with a default (value as? Int ?: 0). Use plain as only when a wrong type would be a real bug.

Note that casting doesn’t convert: "123" as Int fails. To turn text into a number, use toInt(), as covered in the type conversion lesson.

When smart casts don’t work

Kotlin only smart-casts when it can prove the value can’t change between the check and the use:

class Profile {
    var nickname: String? = null
}

fun greet(p: Profile) {
    if (p.nickname != null) {
        // println(p.nickname.length)   // ❌ another thread could change nickname in between
    }
    p.nickname?.let { println(it.length) }   // ✅ ?.let works on a safe local copy
}

Smart casts work for local vals, local vars that aren’t changed in a lambda, and val properties without a custom getter in the same module. For a mutable property, copy it to a local val first, or use ?.let.

filterIsInstance

To keep only the items of one type from a list:

fun main() {
    val mixed: List<Any> = listOf(1, "two", 3, "four", 5.0)
    val texts: List<String> = mixed.filterIsInstance<String>()
    println(texts.map { it.uppercase() })
    println(mixed.filterIsInstance<Int>().sum())
}

Output:

[TWO, FOUR]
4

Common mistakes

  • Using as to convert: "5" as Int throws. Use "5".toInt().
  • Expecting a smart cast on a var property: copy it to a local val or use ?.let.
  • Checking is List<String>: generic type arguments are erased at runtime. You can only check is List<*>.

Exercise

Write a function that receives values of any type from a form and returns a cleaned-up description of each.

fun clean(value: Any?): String = when (value) {
    null -> "empty"
    is String -> if (value.isBlank()) "empty" else "text \"${value.trim()}\""
    is Int -> if (value < 0) "invalid number" else "number $value"
    is Boolean -> if (value) "yes" else "no"
    is List<*> -> "list of ${value.size}"
    else -> "unknown (${value::class.simpleName})"
}

fun main() {
    listOf<Any?>("  Asha ", "", -4, 18, true, listOf(1, 2), null, 2.5).forEach { println(clean(it)) }
}

Output:

text "Asha"
empty
invalid number
number 18
yes
list of 2
empty
unknown (Double)

FAQ

What is a smart cast in Kotlin?

After you check a value’s type with is (or check it isn’t null), Kotlin automatically treats it as that type, so you don’t need to cast it yourself.

What is the difference between as and as? in Kotlin?

as throws a ClassCastException if the type is wrong. as? returns null instead.

Why does Kotlin say “smart cast is impossible”?

The value could change between the check and the use, usually because it’s a var property. Copy it to a local val first.

WhatsApp us📞 Call now