Smart casts with the K2 compiler
suggest changeA smart cast happens when the compiler can prove that a value has a narrower type than the one it was declared with. After if (x is String) or if (x != null) you can use x as a String (or as a non-null type) without writing as or !!. The basics are in Smart casts.
Kotlin 2.0 shipped a new compiler front-end, K2. It rebuilt the data-flow analysis that smart casts depend on, and it now smart casts in many places where the old K1 compiler gave up:
| Situation | K1 (Kotlin 1.9 and older) | K2 (Kotlin 2.0+) |
|---|---|---|
Check stored in a local Boolean (val ok = x != null; if (ok) ...) |
no smart cast | smart cast |
x is A || x is B, or is A, is B -> in when |
x stays Any |
cast to the closest common supertype |
local var changed inside an inline lambda (forEach, repeat, let) |
no smart cast | smart cast |
nullable property of function type (val onClick: (() -> Unit)?) |
needed onClick?.invoke() |
onClick() after a null check |
catch and finally after reassigning a var in try |
could keep a wrong smart cast | knows the value may have changed |
++x where inc() returns a different type |
kept the old (wrong) type | uses the return type of inc() |
All of this is stable and on by default since Kotlin 2.0. No flag or opt-in is needed. Kotlin 2.4 no longer accepts -language-version 1.9, so the K1 behavior can't be turned back on.
All examples were compiled and run with Kotlin 2.4.21 on JDK 25.
A quick recap
The classic smart casts work after is, !is, == null and != null checks, in if, when, while, on the right side of && and ||, and after an early return:
sealed interface Shape
data class Circle(val radius: Double) : Shape
data class Rect(val w: Double, val h: Double) : Shape
fun describe(x: Any?): String {
if (x == null) return "null"
// x is Any here, not Any?
if (x is String && x.isNotEmpty()) return "string of length ${x.length}"
if (x !is Number) return "something else: ${x::class.simpleName}"
// x is Number from here on
return "number ${x.toDouble()}"
}
fun area(s: Shape): Double = when (s) {
is Circle -> Math.PI * s.radius * s.radius
is Rect -> s.w * s.h
}
fun main() {
println(describe(null))
println(describe("hello"))
println(describe(42))
println(describe(listOf(1)))
println("%.2f".format(area(Circle(1.0))))
println(area(Rect(2.0, 3.0)))
}
Output:
null
string of length 5
number 42.0
something else: SingletonList
3.14
6.0
when over a sealed type is covered in Sealed classes and interfaces, and smart casts inside when guards in Guard conditions in when.
Safe calls compared with null or with a Boolean also smart cast, and so do loops that check the loop variable:
class Node(val value: Int, val next: Node?)
class User(val name: String, val email: String?)
fun main() {
var node: Node? = Node(1, Node(2, Node(3, null)))
while (node != null) {
print("${node.value} ")
node = node.next
}
println()
val user: User? = User("ann", "ann@example.com")
if (user?.email != null) {
// both user and user.email are smart cast
println("${user.name}: ${user.email.length}")
}
val s: String? = " "
if (s?.isBlank() == true) println("blank, length ${s.length}")
}
Output:
1 2 3
ann: 15
blank, length 2
Checks stored in local Boolean variables
With K1, a smart cast only happened when the check was written directly in the if condition. If you gave the check a name, the information was lost. K2 remembers what a local val of type Boolean means:
class User(val name: String, val email: String?)
fun sendWelcome(user: User?) {
val canEmail = user != null && user.email != null
val label = if (user != null) user.name else "guest"
println("label: $label")
if (canEmail) {
// user is User and user.email is String here
println("sending to ${user.email.lowercase()} for ${user.name}")
} else {
println("can't email $label")
}
}
fun main() {
sendWelcome(User("Ann", "ANN@EXAMPLE.COM"))
sendWelcome(User("Bob", null))
sendWelcome(null)
}
Output:
label: Ann
sending to ann@example.com for Ann
label: Bob
can't email Bob
label: guest
can't email guest
Inside if (canEmail) both user and user.email are smart cast, because canEmail is true only when both checks passed.
Named checks can build on each other, and the negated form works with early returns. Functions with contracts, like isNullOrBlank(), work too:
class Cat(val lives: Int) { fun meow() = println("meow ($lives lives)") }
fun petSound(animal: Any) {
val isCat = animal is Cat
val isLoud = isCat && animal.lives > 5 // animal is Cat after isCat &&
if (isLoud) animal.meow()
}
fun greet(name: String?) {
val missing = name.isNullOrBlank()
if (missing) {
println("hello, stranger")
return
}
println("hello, ${name.trim()}") // name is String
}
fun len(x: Any): Int {
val notString = x !is String
if (notString) return -1
return x.length // x is String
}
fun main() {
petSound(Cat(9))
petSound(Cat(1))
petSound("dog")
greet(null)
greet(" Ann ")
println(len(3))
println(len("four"))
}
Output:
meow (9 lives)
hello, stranger
hello, Ann
-1
4
This lets you give complex conditions a readable name without adding !! later.
It only works for a val. If the flag is a var, it could be changed between the check and the use, and a local function is not analyzed either:
fun f(input: String?) {
var ok = input != null
if (ok) println(input.length)
}
fun h(x: Any) {
fun check() = x is String
if (check()) println(x.length)
}
boolbad.kt:3:26: error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'String?'.
if (ok) println(input.length)
^
boolbad.kt:8:28: error: unresolved reference 'length' on receiver of type 'Any'.
if (check()) println(x.length)
^^^^^^
The value being checked must also not change: if you reassign input after val ok = input != null, the smart cast follows the new value, not the old check.
|| checks cast to a common supertype
When K1 saw x is A || x is B, it didn't smart cast at all, and x kept its declared type. K2 smart casts x to the closest supertype that A and B have in common:
sealed interface PaymentResult
interface HasReason { val reason: String }
data object Paid : PaymentResult
data class Declined(override val reason: String, val code: Int) : PaymentResult, HasReason
data class Refunded(override val reason: String, val amount: Int) : PaymentResult, HasReason
fun report(r: PaymentResult) {
if (r is Declined || r is Refunded) {
// r is smart cast to HasReason, the closest common supertype
println("problem: ${r.reason}")
} else {
println("ok: $r")
}
}
fun main() {
report(Paid)
report(Declined("card expired", 54))
report(Refunded("duplicate order", 30))
}
Output:
ok: Paid
problem: card expired
problem: duplicate order
You only get the members of the common supertype. r.code exists only on Declined, so it's an error:
orbad.kt:8:19: error: candidate 'val Char.code: Int' is inapplicable because of a receiver type mismatch.
println(r.code)
^^^^
(The message is confusing: the compiler can't find code on HasReason, so it reports the closest match it found, the Char.code extension.)
A when branch with several conditions separated by commas is the same as ||, so it smart casts too. Here Int, Long and Double have Number in common:
fun toDouble(x: Any): Double? = when (x) {
is Int, is Long, is Double -> x.toDouble() // x is Number
is String -> x.toDoubleOrNull()
else -> null
}
fun main() {
println(listOf(1, 2L, 2.5, "3.5", "abc", 'c').map(::toDouble))
}
Output:
[1.0, 2.0, 2.5, 3.5, null, null]
If the only common supertype is Any, the smart cast gives you nothing useful. To make this work for your own classes, give them a shared interface, as HasReason does above.
Local variables changed inside inline lambdas
K1 treated every lambda the same: if a lambda assigned a local var, that variable could not be smart cast anywhere near the lambda, because the lambda might run later, on another thread. For inline functions like forEach, repeat, let or run this was too strict. The compiler copies an inline lambda into the caller, so it runs right there, in order.
K2 knows this and smart casts such variables:
data class Product(val name: String, val price: Int)
fun cheapest(products: List<Product>): Product? {
var best: Product? = null
products.forEach { p ->
// best is a local var modified inside an inline lambda;
// K2 still smart casts it after the null check
if (best == null || p.price < best.price) {
best = p
}
}
return best
}
fun main() {
val items = listOf(Product("pen", 3), Product("ink", 2), Product("pad", 5))
println(cheapest(items))
println(cheapest(emptyList()))
var cached: String? = null
repeat(3) { i ->
if (cached == null) cached = "computed at $i"
println(cached.uppercase())
}
}
Output:
Product(name=ink, price=2)
null
COMPUTED AT 0
COMPUTED AT 0
COMPUTED AT 0
In best == null || p.price < best.price, the right side of || runs only when best isn't null, so best.price compiles. With K1 you had to write best!!.price or copy best into a local val.
This doesn't apply to lambdas that are not inline. Sequence.onEach and the Thread constructor store the lambda and call it later, so the compiler still refuses:
data class Product(val name: String, val price: Int)
fun cheapestLazy(products: Sequence<Product>): Product? {
var best: Product? = null
products.onEach { p ->
if (best == null || p.price < best.price) best = p
}.count()
return best
}
fun main() {
var counter: Int? = 0
val t = Thread { counter = null }
if (counter != null) {
t.start()
println(counter + 1)
}
}
lambad.kt:6:39: error: smart cast to 'Product' is impossible, because 'best' is a local variable that is mutated in a capturing closure.
if (best == null || p.price < best.price) best = p
^^^^
lambad.kt:16:17: error: smart cast to 'Int' is impossible, because 'counter' is a local variable that is mutated in a capturing closure.
println(counter + 1)
^^^^^^^
The second error catches a real bug: after t.start() the other thread can set counter to null at any moment, so counter + 1 could fail.
Nullable properties of function type
A property that holds an optional callback has a nullable function type. K1 didn't smart cast it for a call, so you wrote onClick?.invoke(). K2 lets you call it directly after a null check:
class Button(val label: String, val onClick: (() -> Unit)? = null) {
fun click() {
if (onClick != null) {
onClick() // K2: smart cast to () -> Unit, no ?.invoke() needed
} else {
println("$label: no handler")
}
}
}
fun main() {
Button("Save") { println("saving") }.click()
Button("Help").click()
}
Output:
saving
Help: no handler
The usual property rules still apply (see below): this works because onClick is a final val declared in the same module.
try, catch and finally
An exception can be thrown at any point in a try block, so in catch and finally the compiler can't assume that the assignments in try happened. K1 sometimes got this wrong and kept a smart cast from before the try, even after the variable was set to null inside it. K2 merges the possible states correctly.
Here token is smart cast to String at the start of try. Then it's reassigned to a nullable value, and an exception may follow:
val cache = mutableMapOf("token" to "abc123")
fun fetchNewToken(): String? = null // the server said no
fun refresh() {
var token: String? = cache["token"]
if (token == null) return
try {
println("old token ${token.uppercase()}") // token is String
token = fetchNewToken() // may be null now
check(token != null) { "refresh failed" }
cache["token"] = token // String again after check()
} catch (e: IllegalStateException) {
// the exception may have come after token was set to null
println("${e.message}, token = ${token?.uppercase()}")
}
}
fun main() = refresh()
Output:
old token ABC123
refresh failed, token = null
In the catch block token is String? again, and the ?. is required. Writing token.uppercase() there is an error:
trycatch5.kt:15:47: error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'String?'.
println("${e.message}, token = ${token.uppercase()}")
^
K1 accepted that line (and even reported the ?. as unnecessary), so the code could fail with a NullPointerException at run time.
The same applies to finally. A common pattern is a resource variable that starts as null and is assigned inside try:
class Connection(val host: String) {
init {
if (host.isEmpty()) throw IllegalArgumentException("no host")
}
fun send(msg: String) = println("$host <- $msg")
fun close() = println("closed $host")
}
fun deliver(host: String, msg: String) {
var conn: Connection? = null
try {
conn = Connection(host)
conn.send(msg) // smart cast to Connection after the assignment
} catch (e: IllegalArgumentException) {
println("failed: ${e.message}")
} finally {
// the constructor may have thrown, so conn is Connection? again
conn?.close()
}
}
fun main() {
deliver("db1", "hello")
deliver("", "hello")
}
Output:
db1 <- hello
closed db1
failed: no host
After conn = Connection(host) the variable is smart cast to Connection, so conn.send(msg) needs no ?.. In finally it's Connection?, because the constructor may have thrown before the assignment.
Note that assignment smart casts a var, but its initializer doesn't. var conn: Connection? = Connection(host) keeps the declared type Connection?, so conn.send(msg) right after it is an error. The explicit type annotation wins.
Increment and decrement operators
++x is x = x.inc(), and inc() may return a different type than x had. K1 kept the old smart cast after ++, which could be wrong. K2 uses the return type of inc():
interface Version {
val n: Int
operator fun inc(): Released = Released(n + 1)
}
interface Signed { val signature: String }
data class Released(override val n: Int) : Version {
fun publish() = println("published v$n")
}
class SignedDraft(override val n: Int, override val signature: String) : Version, Signed
fun ship(start: Version) {
var v = start // v: Version
if (v is Signed) {
println("signed by ${v.signature}")
++v // v now holds a Released
v.publish() // smart cast to Released
}
}
fun main() = ship(SignedDraft(1, "kjk"))
Output:
signed by kjk
published v2
After ++v the old is Signed information is gone, because Released isn't Signed:
incr2.kt:17:19: error: unresolved reference 'signature' on receiver of type 'Released'.
You'll rarely write such operators, but the rule shows how K2 works: every assignment, including the hidden one in ++, resets what the compiler knows about the variable.
What still doesn't smart cast
A smart cast is only allowed when the compiler can prove that the value can't change between the check and the use. These rules didn't change in K2:
open class Profile(
val nickname: String?, // final val, same module: OK
var status: String?, // var: no
open val avatar: String?, // open: no
) {
val bio: String? get() = null // custom getter: no
val lazyName: String? by lazy { "x" } // delegated: no
fun show() {
if (nickname != null) println(nickname.length)
if (status != null) println(status.length)
if (avatar != null) println(avatar.length)
if (bio != null) println(bio.length)
if (lazyName != null) println(lazyName.length)
}
}
props.kt:11:37: error: smart cast to 'String' is impossible, because 'status' is a mutable property that could be mutated concurrently.
if (status != null) println(status.length)
^^^^^^
props.kt:12:37: error: smart cast to 'String' is impossible, because 'avatar' is a property that has an open or custom getter.
if (avatar != null) println(avatar.length)
^^^^^^
props.kt:13:34: error: smart cast to 'String' is impossible, because 'bio' is a property that has an open or custom getter.
if (bio != null) println(bio.length)
^^^
props.kt:14:39: error: smart cast to 'String' is impossible, because 'lazyName' is a delegated property.
if (lazyName != null) println(lazyName.length)
^^^^^^^^
varproperties: another thread, or a function you call, can change them.openproperties and custom getters: each read runs a getter, which can return a different value each time. A subclass could overrideavatarwith such a getter.- delegated properties: each read calls the delegate's
getValue. - properties from another module: a public
valin a library may become avaror get a custom getter in a later version, without your code being recompiled.
The last rule shows up when you use a class from a library. Here Account is compiled as module lib and used from module app:
// module lib
package lib
class Account(val email: String?)
// module app
import lib.Account
fun main() {
val a = Account("ann@example.com")
if (a.email != null) println(a.email.length)
}
app\main.kt:4:34: error: smart cast to 'String' is impossible, because 'email' is a public API property declared in different module.
if (a.email != null) println(a.email.length)
^^^^^^^
The same code compiles when Account is in the same module. In a multi-project Gradle build, each subproject is a separate module.
Local vars captured and changed by a non-inline lambda (shown above) are the other common case.
Working around it
When a smart cast isn't possible, read the value once into something that can't change:
class Settings {
var theme: String? = null // mutable property: never smart cast
}
fun applyTheme(s: Settings) {
// 1. copy into a local val
val theme = s.theme
if (theme != null) println("1: ${theme.uppercase()}")
// 2. bind it in when
when (val t = s.theme) {
null -> println("2: default theme")
else -> println("2: ${t.length} chars")
}
// 3. safe call with let
s.theme?.let { println("3: ${it.lowercase()}") }
// 4. elvis with return
val t = s.theme ?: return
println("4: $t")
}
fun parse(input: Any?) {
requireNotNull(input) { "input is required" }
// input is Any from here (contract in requireNotNull)
input as String // throws if not a String
println(input.trim()) // input is String
val words: List<String>? = input.split(" ").takeIf { it.size > 1 }
if (!words.isNullOrEmpty()) println(words.first()) // contract: words is List<String>
}
fun main() {
applyTheme(Settings().apply { theme = "Dark" })
applyTheme(Settings())
parse(" hello world ")
}
Output:
1: DARK
2: 4 chars
3: dark
4: Dark
2: default theme
hello world
The second call returns at step 4 because theme is null.
Copying into a local val is also more correct, not just a way to please the compiler: the code works on one snapshot of the value, even if another thread changes the property in the meantime.
The last function shows two more sources of smart casts:
- a cast with
as: afterinput as String,inputis aStringfor the rest of the scope, because the cast would have thrown otherwise. - contracts: stdlib functions such as
require,requireNotNull,check,checkNotNull,isNullOrEmptyandisNullOrBlankdeclare contracts that tell the compiler what's true after they return. Writing your own contracts withkotlin.contractsstill requires@OptIn(ExperimentalContracts::class)in Kotlin 2.4.
Summary
| You write | Smart cast in K2? |
|---|---|
if (x != null), if (x is T), when (x) { is T -> } on a local or a final same-module val |
yes |
val ok = x != null; if (ok) |
yes (since 2.0) |
x is A || x is B, is A, is B -> |
yes, to the common supertype (since 2.0) |
local var assigned inside forEach/let/repeat |
yes (since 2.0) |
val f: (() -> Unit)? then if (f != null) f() |
yes (since 2.0) |
var changed in try, used in catch/finally |
only if it's non-null on every path |
var, open, custom-getter or delegated property |
no, copy to a local val |
| public property from another module | no, copy to a local val |
local var changed in a non-inline lambda |
no |
For more on nullable types, see Nullable and Non-Nullable types. Type checks on class hierarchies are covered in Polymorphism.