is and !is

Checking a Type at Runtime

x is Type returns true if x is an instance of Type (or a subtype). !is is the opposite. It works like Java's instanceof.

Example

fun describe(x: Any): String = when (x) {
    is Int -> "Int"
    is String -> "String"
    is List<*> -> "List"
    !is Number -> "Something else: ${x::class.simpleName}"
    else -> "Some other number"
}

fun main() {
    println(describe(5))
    println(describe("hi"))
    println(describe(listOf(1)))
    println(describe(true))
    println(describe(2.5))
}

Output

Int
String
List
Something else: Boolean
Some other number