Kotlin example

How to check a type at runtime in Kotlin

10 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use is, Kotlin's instanceof: if (x is String) checks the type, and inside the block the compiler smart-casts x to String, so you call x.length without a cast. For several types, write when (x) { is String -> …; is Int -> … }. To read the type as text, use x::class.simpleName; Java's getClass() is x.javaClass.

Kotlin checks types with operators, not methods: is and !is test a value, as and as? cast it, and the compiler remembers a passed check, so most code needs no cast at all. The sections below cover is with smart casts and when, the two casts, getting the class and its name, generic types (where erasure gets in the way and reified and filterIsInstance help), the "Smart cast is impossible" compile error and its fixes, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1is, !is, smart casts and whenRecommended

x is String is true when x holds a String or a subtype, like Java's x instanceof String, and x !is String is its negation. The difference from Java is what happens next: after a passed check the compiler smart-casts x, so inside the if, on the right of &&, and after an early return on !is, you use x as a String with no (String) x cast. For several types, when (x) { is … } is the switch on type, and each branch gets its own smart cast. The is Int if x > 100 branch is a guard condition, stable since Kotlin 2.2; on an older version, put an if inside the is Int branch instead.

IsSmartCast.kt
fun describe(x: Any?): String = when (x) {
    null -> "null"
    is String -> "String of length ${x.length}"
    is Int if x > 100 -> "big Int $x"
    is Int -> "Int, doubled ${x * 2}"
    is List<*> -> "List with ${x.size} items"
    else -> "something else: ${x::class.simpleName}"
}

fun shout(x: Any): String {
    // !is plus an early return: x is a String after this line
    if (x !is String) return "not text"
    return x.uppercase() + "!"
}

fun main() {
    val value: Any = "kotlin"

    // is is Kotlin's instanceof
    if (value is String) {
        // Smart cast: value is a String here, no cast needed
        println("${value.length} letters")
    }
    println(value is CharSequence)
    println(value is Int)
    println(value !is Int)

    // && smart-casts the right-hand side too
    if (value is String && value.startsWith("k")) println("starts with k")

    // when (x) { is ... } is the switch on type
    for (x in listOf("hi", 21, 500, listOf(1, 2, 3), 2.5, null)) {
        println(describe(x))
    }

    println(shout("hey"))
    println(shout(7))

    // null is no instance of String, but it is a String?
    val nothing: Any? = null
    println("${nothing is String} ${nothing is String?}")
}

Output

Inside the if, value.length compiles with no cast and prints 6 letters. value is CharSequence is true because String implements that interface: like instanceof, is accepts supertypes. In describe, 21 takes the plain is Int branch (Int, doubled 42) and 500 the guarded one (big Int 500), while 2.5 falls through to else as Double. The last line prints false true: null is never an instance of String, but it is a valid String?. The list branch says is List<*>, not is List<Int>, for a reason covered in section 4.

2Casting with as and as?

When you need the cast itself, x as String gives x typed as String and throws ClassCastException when it is something else. The safe cast x as? String gives null instead, which pairs with the Elvis operator: (x as? Int) ?: 0. A cast never converts a value: "42" as Int fails, and you want toInt() for that. The same goes for numbers: a boxed Int is not a Long.

AsSafeCast.kt
fun main() {
    val value: Any = "42"

    // as? gives null when the type does not match
    println(value as? Int)
    println((value as? Int) ?: 0)

    // as on the wrong type throws ClassCastException
    try {
        val n = value as Int
        println(n)
    } catch (e: ClassCastException) {
        println(e.message?.substringBefore(" ("))
    }

    // as on the right type: text is typed as String from here on
    val text = value as String
    println(text.length)

    // A cast never converts: use toInt() to turn text into a number
    println(text.toInt() + 1)

    // Boxed numbers do not widen either: an Int is not a Long
    val five: Any = 5
    println(five as? Long)
    println((five as Int).toLong())

    // null: as String? and as? String give null, as String throws
    val missing: Any? = null
    println(missing as String?)
    println(missing as? String)
    try {
        println(missing as String)
    } catch (e: NullPointerException) {
        println(e.message)
    }
}

Output

value as? Int prints null, and with the Elvis 0. The hard cast throws, and its message (cut at the parenthesis) reads class java.lang.String cannot be cast to class java.lang.Integer. Once value as String succeeds, text is a String: text.length gives 2 and text.toInt() + 1 gives 43. The boxed 5 is no Long, so as? Long gives null; toLong() is the conversion. For null, as String? and as? String both give null, and as String throws NullPointerException with null cannot be cast to non-null type kotlin.String.

3Get the class and its name: ::class, javaClass, simpleName

x::class gives the runtime class of a value as a KClass; its simpleName is the short name and qualifiedName the full one. Java's x.getClass() is x.javaClass (or x::class.java), which you need for Java APIs such as Gson's fromJson(json, User::class.java). A class literal is String::class, the Kotlin form of String.class. To ask "is this exactly a Dog" rather than "a Dog or a subclass", compare classes with ==.

ClassName.kt
open class Animal
class Dog : Animal()
data class User(val name: String)

fun main() {
    val items = listOf("text", 42, 3.14, User("Ada"), listOf(1, 2))
    for (item in items) {
        // ::class is the runtime class; simpleName is its short name
        println("${item::class.simpleName} | ${item::class.qualifiedName}")
    }

    // javaClass (or ::class.java) is Java's getClass()
    val text: Any = "text"
    println(text.javaClass.name)
    println(text::class.java.simpleName)

    // A plain Int is the JVM primitive; stored as Any it is boxed
    val n = 42
    val boxed: Any = n
    println(n.javaClass)
    println(boxed.javaClass)

    // is accepts subclasses; == on classes wants the exact class
    val pet: Any = Dog()
    println(pet is Animal)
    println(pet::class == Animal::class)
    println(pet::class == Dog::class)
    println(Animal::class.isInstance(pet))

    // ::class is the object's class, not the declared type
    val name: CharSequence = "Ada"
    println(name::class.simpleName)
}

Output

Each line shows the short and the full name, such as Int | kotlin.Int; User | User has no prefix because the class sits in no package. Note ArrayList | java.util.Arrays.ArrayList for listOf(1, 2): ::class reports the class the object really is, an internal detail of listOf, so don't build logic on those names. The JVM name of a string is java.lang.String. A plain Int prints as the primitive int and the boxed one as class java.lang.Integer. The Dog passes is Animal, fails pet::class == Animal::class and passes == Dog::class; isInstance is the is check for a class you hold in a variable. The last line prints String, not CharSequence.

4Generic types: erasure, filterIsInstance and reified

On the JVM, type arguments are erased at runtime: a List<String> and a List<Int> are both just a List. So x is List<String> doesn't compile; here the error reads Cannot check for instance of erased type 'List<String>'. Check is List<*> and then the elements, or let filterIsInstance<T>() pick the items of one type and hand you a typed list. Inside a function, is T fails the same way (Cannot check for instance of erased type 'T (of fun <T> isA)'.) unless the function is inline and T is reified: the compiler then copies the body into each call with the real type, so is T, as? T and T::class work.

ReifiedErasure.kt
data class Waypoint(val name: String)

// reified keeps T at runtime, so as? T really checks the type
inline fun <reified T> Map<String, Any?>.getAs(key: String): T? =
    this[key] as? T

inline fun <reified T : Any> typeName(): String = T::class.simpleName ?: "?"

fun main() {
    val mixed: List<Any?> = listOf(Waypoint("A"), "note", Waypoint("B"), null, 7)

    // filterIsInstance keeps one type and gives you a typed list
    val points: List<Waypoint> = mixed.filterIsInstance<Waypoint>()
    println(points)
    println(mixed.filterIsInstance<String>())

    // Erasure: is List<*> checks the container, not what is inside
    val data: Any = listOf("x", "y")
    println(data is List<*>)
    println(data is List<*> && data.all { it is String })

    // reified type parameters are real types at runtime
    val settings = mapOf("host" to "localhost", "port" to 8080)
    val port: Int? = settings.getAs("port")
    val host: Int? = settings.getAs("host")
    println("port=$port host=$host")
    println(typeName<Waypoint>())

    // An unchecked cast compiles, and checks nothing until you read an item
    @Suppress("UNCHECKED_CAST")
    val unchecked = mixed as List<Waypoint>
    println(unchecked.size)
    try {
        println(unchecked[1].name)
    } catch (e: ClassCastException) {
        println(e.message?.substringBefore(" ("))
    }
}

Output

filterIsInstance<Waypoint>() skips the string, the null and the 7 and gives [Waypoint(name=A), Waypoint(name=B)], typed List<Waypoint>. Because T is reified, getAs returns port=8080 host=null: as? T really compares with Int and turns down "localhost". Written without reified, the same function compiles (with an unchecked-cast warning) but as? T checks nothing: it hands back localhost instead of null, and the program throws ClassCastException later, where the value is used as an Int. The unchecked list cast shows the same delay: unchecked.size prints 5, and only reading item 1 fails with class java.lang.String cannot be cast to class Waypoint.

5The compile error: “Smart cast to … is impossible”

Smart casts work on local values, but not on a var property of a class: between the check and the use, another thread could assign a different value, so the compiler refuses to trust the check. The program below never runs. Older Kotlin versions worded this error "… is a mutable property that could have been changed by this time"; the K2 compiler in Kotlin 2 says "could be mutated concurrently". Both mean the same thing, and the same error appears after a != null check on a nullable var property.

SmartCastError.kt
class Ticket(var label: Any?)

fun main() {
    val ticket = Ticket("VIP")
    if (ticket.label is String) {
        println(ticket.label.length)
    }
}

Output

The compiler stops at line 6 with Smart cast to 'String' is impossible, because 'label' is a mutable property that could be mutated concurrently. Two relatives, from runs here: a property with a custom getter or an open one (whose getter may return something new on each call) gives Smart cast to 'String' is impossible, because 'label' is a property that has an open or custom getter. A local var that a lambda assigns gives … because 'x' is a local variable that is mutated in a capturing closure. The next section has the fixes.

6Fixing the smart cast error

Every fix comes down to checking and using the same value. Copy the property into a local val and check the copy, give when a subject variable with when (val l = ticket.label) { … }, or cast once with as? and continue in ?.let. Inside the class, the same local copy works. Don't reach for ticket.label as String or !! here: they compile, but they read the property again and only move the problem to runtime.

SmartCastFix.kt
class Ticket(var label: Any?) {
    // Inside the class, the same local copy works
    fun describe(): String {
        val current = label
        return if (current is String) "text of ${current.length}" else "not text"
    }
}

// A val property with no custom getter smart-casts directly
class Badge(val label: Any?)

fun main() {
    val ticket = Ticket("VIP")

    // 1. Copy the property into a local val, then check the copy
    val label = ticket.label
    if (label is String) println(label.length)

    // 2. Give when a subject val
    when (val l = ticket.label) {
        is String -> println("String ${l.lowercase()}")
        is Int -> println("Int ${l + 1}")
        else -> println("other")
    }

    // 3. Cast once with as? and continue in let
    (ticket.label as? String)?.let { println(it.uppercase()) }

    // 4. A method that copies the property first
    println(ticket.describe())
    ticket.label = 7
    println(ticket.describe())

    // 5. A val property needs no copy
    val badge = Badge("guest")
    if (badge.label is String) println(badge.label.length)
}

Output

Each fix reads the property once: the local copy prints 3, the when subject String vip, and the as? with let prints VIP. describe() gives text of 3, then not text after ticket.label = 7, because it copies the current value on every call. The Badge prints 5 with no copy at all: a val property with a plain backing field, declared in the same module and not open, can't change, so the smart cast is allowed. If the property does not need to change, making it a val is the simplest fix.

7Which should you use?

MethodGivesWrong typeBest for
if (x is T) { … }Boolean + smart castSkips the blockOne type, then code that uses it
when (x) { is T -> … }Smart cast per branchNext branch or elseSeveral types, sealed classes
(x as? T) ?: defaultT? (null on mismatch)nullOne expression with a fallback
list.filterIsInstance<T>()List<T>Item left outMixed lists, instead of an unchecked cast
inline fun <reified T>is T works in genericsAs is / as?Helpers that take a type, T::class.java for Java APIs
x::class.simpleNameThe class nameNot a checkLogs and messages; x.javaClass for Java APIs
x as TTClassCastExceptionValues that are T unless your code has a bug

Frequently asked questions

What is the Kotlin equivalent of Java's instanceof?

The is operator: x is String is true when x is a String or a subtype, and x !is String is the negation. Unlike Java, you don't cast afterward: inside if (x is String) { … } the compiler smart-casts x, so x.length compiles. For several types, use when (x) { is String -> …; is Int -> … }.

What is the Kotlin equivalent of getClass()?

x.javaClass gives the java.lang.Class, the same as Java's x.getClass(), and x::class.java gives the same object. x::class gives Kotlin's KClass. For a type rather than a value, write String::class (Kotlin) or String::class.java (Java, the old String.class), which is what Java APIs like Gson ask for.

How do I get the type of a variable as a string?

Use x::class.simpleName for the short name (String) or x::class.qualifiedName for the full one (kotlin.String); x.javaClass.name gives the JVM name (java.lang.String). Both Kotlin properties return String?: here a local class has a qualifiedName of null and an anonymous object {} has a simpleName of null. They show the runtime class, so listOf(1, 2) reports ArrayList.

How does the reified keyword work?

Type arguments are erased at runtime, so a normal generic function cannot check is T or read T::class. Marking the type parameter reified in an inline function fixes that: the compiler copies the function body into every call site with the real type filled in, so is T, as? T, T::class and T::class.java all work. The cost is that the function must be inline and cannot be called from Java.

How do I check a generic type like List<String>?

You can't check it directly: x is List<String> fails with Cannot check for instance of erased type 'List<String>'. because the JVM erases the element type. Check x is List<*>, then the elements (x.all { it is String }), or use x.filterIsInstance<String>() to get a List<String> of the items that match.

How do I fix "Unchecked cast: List<Any?> to List<Waypoint>"?

Replace the cast with list.filterIsInstance<Waypoint>(), which checks each item and returns a real List<Waypoint>. The unchecked list as List<Waypoint> checks nothing: it succeeds even when the list holds a String, and the ClassCastException comes later, at the line that reads that item. Suppress the warning only when you know every item has the type.

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

x as String is an unsafe cast: it throws ClassCastException when x is not a String, and NullPointerException with null cannot be cast to non-null type kotlin.String when x is null. x as? String is the safe cast: it returns null in both cases, so the result type is String?. Neither one converts values; "42" as Int fails, and "42".toInt() is the conversion.

Run it yourself

Open any of these in the full Kotlin editor to tweak, run and share.

Kotlin playground