CodeGym /Courses /Kotlin SELF /Type checks and casts: is, smart cast, as, as?

Type checks and casts: is, smart cast, as, as?

Kotlin SELF
Level 34, Lesson 3
Available

1. Introduction

When you’re just starting to program, it seems logical: “Well, I wrote val x: String, so it’s a string — that’s it.” In most cases that’s true, and Kotlin does everything it can to let you live peacefully. But as soon as you start writing functions that accept a more general type (for example, Any or a base class), you run into reality: different kinds of data can end up in this variable. And then the question arises: “What exactly is in there right now, and can I call methods on this object?”

Imagine our console expense tracker (a hypothetical course app): it has an “internal” model Expense, and user input is a string. Sometimes we want to write a helper function that can accept “something” (a string, a number, null) and try to turn it into an amount. Or we write a handler for an operation result, where a general type is returned, but internally there are different result variants. In such places Kotlin asks us to be honest: first check the type, then use it.

Any and Any?: the most general type

If Kotlin is a strict teacher, then Any is its phrase: “Fine, bring me anything, but later I’ll ask what you brought.” Type Any means “any non-null object.” This is important: null is not a value of type Any, because Any is non-null. If you want “anything, including null,” that would be Any?.

Any is useful when you genuinely don’t know the exact type ahead of time: for example, in a collection of “mixed” values, in a universal parser, in a logging function, in an adapter over third-party data. But Any comes with a cost: while a variable is of type Any, you can’t just call String methods or access .length. First you need to prove to the compiler that it’s actually a string (or another specific type).

A small table to reinforce this:

Type What it means Can it hold null
Any
any object no
Any?
any object or null yes

2. Type check: is and !is

The is operator is your “type detector.” It checks at runtime whether a value belongs to the specified type. If yes, the condition is true; if not, it’s false. There’s also !is if you prefer reading the check as “not that type.”

The best part: is usually triggers a smart cast. That is, inside the if branch Kotlin allows you to treat the variable as a more specific type — without an explicit as. More on that in the next section, but for now—here’s a small example.

fun printLength(x: Any) {
    if (x is String) {
        println(x.length) // for example: 5
    } else {
        println("This is not a string")
    }
}

fun main() {
    printLength("Hello")  // 5
    printLength(42)       // This is not a string
}

Here x on the outside is Any, but inside if (x is String) it becomes “as if it were a String.” That’s smart cast in action.

4. Smart cast: the compiler “figured it out” if you don’t get in its way

Smart cast isn’t magic; it’s careful control-flow analysis. The compiler looks at your checks (is, != null, some conditions) and concludes: “in this branch the value is definitely not null” or “in this branch the value is definitely a String.” After that, it lets you use it as a more specific type without an explicit cast.

In Kotlin with the K2 compiler (starting with Kotlin 2.0), smart cast became possible in more situations than before: for example, when you moved the type check into a separate boolean variable and use it in if.

Let’s look at an example in the style of “our app”: suppose we have a command, and we temporarily store an “argument” as Any (because tests or different data sources may provide different types).

fun normalizeAmount(raw: Any): Int? {
    val isText = raw is String
    if (isText) {
        return raw.toIntOrNull()
    }
    return null
}

In Kotlin 2.x, the compiler better “sees” the connection between isText and the fact that raw can be treated as a String inside the branch.

When smart cast does not work

There are situations where Kotlin will honestly say: “I can’t guarantee the type won’t change.” The most common case is when you check a mutable value that could potentially change between the check and the use. At an introductory level, you can put it like this: smart cast likes val and doesn’t really like var.

Another common scenario: you checked something, but then performed an action after which the value could have changed (or the compiler isn’t sure it didn’t). Then it may “drop confidence” and again require a safe call or an explicit cast. That’s not stubbornness—it’s protection.

5. Unsafe cast: as

Sometimes you’re sure a value has the needed type and you want to explicitly tell Kotlin: “Treat this as a String.” That’s what the as operator is for.

The problem is that as is not a check—it’s an attempt to cast. If the type doesn’t match, the program will crash at runtime with a ClassCastException. So the compiler will accept the code, and the error will only show up when you run it.

A mini example (intentionally “dangerous”):

fun forceString(x: Any): String {
    return x as String
}

fun main() {
    println(forceString("OK")) // OK
    println(forceString(123))  // ClassCastException at runtime
}

Why does this matter right now? Because people often start using as “hoping for the best”: “well, it’s probably a string…”. Don’t do that. as is good when you actually have a strict type guarantee (for example, you put a String there yourself and you never put anything else there).

6. Safe cast: as? and Elvis ?:

The as? operator is a “gentler version” of as. It tries to cast, but if it can’t—it returns null instead of crashing.

This fits perfectly with our earlier experience with nullable types: next you either check for null, or use the Elvis operator ?:.

Example:

fun stringOrNull(x: Any): String? = x as? String

fun main() {
    println(stringOrNull("Hi")?.length) // 2
    println(stringOrNull(123)?.length)  // null
}

Even more practical—immediately provide a “default value”:

fun stringLengthOrZero(x: Any): Int {
    val s = x as? String ?: return 0
    return s.length
}

fun main() {
    println(stringLengthOrZero("Kotlin")) // 6
    println(stringLengthOrZero(10))       // 0
}

This reads straightforwardly: “try to cast to a string; if it doesn’t work—0.”

7. Useful techniques: avoid confusion and write compact code

Comparing is, as, as?

When these three show up next to each other, a beginner’s brain often pretends it’s an old printer: it starts humming and produces a blank page. Let’s nail down the differences in the most down-to-earth way possible.

Tool What it does What it returns If the type doesn’t match
x is T
checks the type
Boolean
just false
x as T
casts the type
T
crashes with ClassCastException
x as? T
casts the type safely
T?
returns null

If you need to “just understand what’s in there”—start with is. If you need to “carefully try to get the needed type”—use as?. Save as for cases where you are truly sure and ready to stand behind that certainty.

when by type and smart cast

Sometimes, instead of multiple if (x is …), it’s more convenient to write a when and check the type in branches. This is especially useful when you have 3–4 expected data shapes and want a neat “processing table.”

fun describeValue(x: Any): String =
    when (x) {
        is String -> "String with length ${x.length}"
        is Int -> "Integer $x"
        else -> "Something else"
    }

fun main() {
    println(describeValue("Hi")) // String with length 2
    println(describeValue(7))    // Integer 7
}

Inside each branch, x is smart-cast to the needed type, and you can safely use .length or print the number. It’s the same principle as in if, just a more compact form.

8. Example: parsing an expense amount from Any?

In real code, the goal is rarely “just cast for the sake of casting.” Usually it’s part of a more meaningful task: parse input, extract a field from a structure, handle different data formats.

Let’s imagine that in our expense tracker there is a function that receives a “raw amount value” from some source. In the simple console variant, that’s a String from readln(), but sometimes we might call the function from a test and pass an Int. We want to make a universal handler that accepts Any? and tries to get the amount in cents (an integer), otherwise returns null.

fun parseAmountCents(raw: Any?): Int? {
    if (raw is Int) return raw
    val text = raw as? String ?: return null
    return text.trim().toIntOrNull()
}

fun main() {
    println(parseAmountCents(" 120 ")) // 120
    println(parseAmountCents(55))      // 55
    println(parseAmountCents("oops"))  // null
}

Notice how this is “grown-up, but without pretension”: first we take the fast path: if it’s already an Int, great. Then we safely try to extract a string via as?. If there’s no string—null. If there is a string—we trim and parse.

A small flowchart

flowchart TD
    A["raw: Any?"] --> B{raw is Int?}
    B -- yes --> C["return raw"]
    B -- no --> D{raw as? String}
    D -- null --> E["return null"]
    D -- String --> F["trim + toIntOrNull()"]
    F --> G["return Int?"]

This diagram is nice because it shows: is is a type-based branch, and as? is an “attempt to extract” the needed type without crashing.

9. Common mistakes when working with is, smart cast, as, as?

Mistake #1: using as as a “type check.”
A very common beginner logic: “if as doesn’t work, then it’s not that type.” But the problem is that “doesn’t work” here means the program crashes with ClassCastException. If the type can vary—start with a check via is or a safe as?, and keep as only for cases with a real guarantee.

Mistake #2: forgetting that as? returns a nullable (T?).
as? doesn’t give you a “clean type,” it gives you a “maybe type.” That’s why code like val s = x as? String; println(s.length) doesn’t compile—and that’s good. The correct continuation is: s?.length, if (s != null), or Elvis ?: for a default value.

Mistake #3: expecting smart cast where the compiler can’t provide a guarantee.
If a value can change (often related to var), the compiler may refuse to smart-cast, because “between the check and the use” the object could theoretically become something else. That’s not nitpicking; it’s a safety measure. In such places, either rewrite the code so that you check and use the value “close together,” or store it in a local val and work with that.

Mistake #4: generalizing everything to Any too early.
Any seems convenient: “one function for everything.” But it comes with a cost: type checks show up almost immediately, when, as?, and the code becomes harder to read. A good rule: use Any only where it’s truly justified by the contract (for example, a universal parser/adapter), and in other places prefer specific types in function parameters.

Mistake #5: mixing “type checking” and “business logic” into one mess.
When inside if (x is String) you start writing 40 lines of logic, the code quickly becomes unreadable. More practical: make a small block where you carefully cast the type (or return an error/null), and only then work with a normal String/Int and write clear domain logic without constant checks.

1
Task
Kotlin SELF, level 34, lesson 3
Locked
Label check
Label check
1
Task
Kotlin SELF, level 34, lesson 3
Locked
First letter
First letter
1
Task
Kotlin SELF, level 34, lesson 3
Locked
Type passport
Type passport
1
Task
Kotlin SELF, level 34, lesson 3
Locked
Title normalization
Title normalization
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION