Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Kotlin Dictionary
  3. Smart Casts / as?

Smart Casts / as?

Kotlin's smart cast automatically applies a cast after a type check using is, eliminating the need for an explicit cast. Use as for an explicit cast, and as? for a safe cast that returns null on failure.

Syntax

// After an is check, smart cast is applied automatically.
fun describe(value: Any) {
    if (value is String) {
        println(value.length)  // Treated as String type.
    }
}

// Use as for an explicit cast (throws ClassCastException on failure).
val str: String = value as String

// Use as? for a safe cast (returns null on failure).
val str: String? = value as? String

// Smart cast in a when expression
when (value) {
    is Int -> println(value * 2)
    is String -> println(value.uppercase())
    is List<*> -> println(value.size)
}

Syntax Reference

SyntaxDescription
value is TypeChecks the type. If true, smart cast is applied in the subsequent block.
value !is TypeNegated type check.
value as TypeExplicit cast. Throws a ClassCastException if the cast fails.
value as? TypeSafe cast. Returns null if the cast fails.
when (value) { is Type -> }Uses smart cast inside a when expression.

Sample Code

// Represent a type hierarchy with a sealed class.
sealed class Shape
data class Circle(val radius: Double) : Shape()
data class Rectangle(val width: Double, val height: Double) : Shape()
data class Triangle(val base: Double, val height: Double) : Shape()

// Call methods on each type using smart cast.
fun area(shape: Shape): Double {
    return when (shape) {
        is Circle -> Math.PI * shape.radius * shape.radius
        is Rectangle -> shape.width * shape.height
        is Triangle -> 0.5 * shape.base * shape.height
    }
}

fun printInfo(value: Any) {
    // Smart cast is applied after each is check.
    when (value) {
        is Int -> println("Int: ${value * 2}")
        is String -> println("String (${value.length} chars): ${value.uppercase()}")
        is List<*> -> println("List (${value.size} items): $value")
        is Boolean -> println("Boolean: $value")
        else -> println("Unknown: $value")
    }
}

fun main() {
    // Basic smart cast usage
    printInfo(42)
    printInfo("Kotlin")
    printInfo(listOf(1, 2, 3))
    printInfo(true)

    // Safe cast with as?
    val obj: Any = "Hello"
    val str: String? = obj as? String
    val num: Int? = obj as? Int  // Cannot cast String to Int, so null
    println("str: $str")   // str: Hello
    println("num: $num")   // num: null

    // Combining as? with ?:
    val length = (obj as? String)?.length ?: 0
    println("length: $length")  // length: 5

    // Smart cast with a sealed class
    val shapes = listOf(
        Circle(5.0),
        Rectangle(4.0, 3.0),
        Triangle(6.0, 4.0)
    )
    shapes.forEach { shape ->
        println("area: ${"%.2f".format(area(shape))}")
    }
}

Notes

Smart cast is a compiler feature that automatically applies a cast after a type check. It works inside the block following an is check, and also on the right-hand side of && conditions. Note that smart cast does not apply to var properties or open properties in some cases.

as? is useful when converting external data or working with values of uncertain type. Because it returns null instead of throwing an exception on failure, you can safely provide a default value using the pattern as? Type ?: defaultValue.

For the basics of nullable types, see Nullable Type / ?. Operator. For using smart cast with sealed classes, see sealed class / sealed interface.

If you find any errors or copyright issues, please .