Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The as operator in Kotlin is an infix operator used for explicit type casting. It instructs the compiler to treat a reference as a specific target type. While it forces a type conversion, the Kotlin compiler still performs static analysis on the cast; it will emit a compile-time error or warning (Cast can never succeed) if it detects an attempt to cast between provably disjoint types (e.g., casting an explicitly typed Int to a String).

Syntax

val castedValue = expression as TargetType

Runtime Behavior

The as operator evaluates the type of the expression at runtime:
  • Success: If the runtime type of the expression is an instance of TargetType (or a subtype), the cast succeeds, and the expression is evaluated as the specified type.
  • Failure: If the runtime type is incompatible with TargetType, the operation throws a ClassCastException (specifically kotlin.ClassCastException, which applies across all Kotlin multiplatform targets including JVM, JS, Native, and Wasm). Because it inherently risks throwing an exception, as is formally designated as the unsafe cast operator.
val obj: Any = "Kotlin"
val str = obj as String  // Succeeds
val num = obj as Int     // Throws ClassCastException

Smart Casting

A critical semantic feature of the as operator is its effect on control flow and scope. When the as operator is used successfully on a variable, it acts as a contract that smart-casts that variable to the target type for the remainder of the current scope. No separate variable assignment is necessary to access the target type’s members after the cast.
fun printLength(obj: Any) {
    obj as String
    // obj is now smart-cast to String for the rest of the scope
    println(obj.length) 
}

Nullability Constraints

The as operator strictly enforces Kotlin’s nullability rules during the cast:
  1. Casting a null reference to a non-nullable type throws a NullPointerException.
  2. To permit a null value to pass through the cast, the target type must be explicitly declared as nullable using the ? suffix.
val obj: Any? = null
val nonNullable = obj as String   // Throws NullPointerException
val nullable = obj as String?     // Succeeds, evaluates to null

The Safe Cast Variant (as?)

To mitigate runtime exceptions, Kotlin provides the safe cast operator as?. If the runtime type is incompatible with the target type, as? suppresses the ClassCastException and instead evaluates to null. Because the result can be null, the expression inherently resolves to a nullable type.
val obj: Any = 123
val str = obj as? String // Succeeds without exception, evaluates to null

Generics and Type Erasure

When using as with parameterized types (generics), the cast is subject to type erasure. Type erasure is a fundamental semantic of Kotlin’s own type system and applies across all compilation targets, not just the JVM. At runtime, the environment can only verify the base class, not the generic type arguments. Casting to a generic type with concrete arguments produces an unchecked cast compiler warning. The cast will succeed at runtime as long as the base type matches, but it compromises type safety, potentially leading to a ClassCastException later in the execution flow when the generic items are accessed.
val mixedList: Any = listOf(1, 2, 3)
// Generates "Unchecked cast: Any to List<String>" warning
val stringList = mixedList as List<String> 
To perform a checked cast on a generic type without warnings, the target type must use a star projection (*), which casts to the base type while leaving the generic argument unknown.
val genericList = mixedList as List<*>
Master Kotlin with Deep Grasping Methodology!Learn More