TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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
Runtime Behavior
Theas 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 aClassCastException(specificallykotlin.ClassCastException, which applies across all Kotlin multiplatform targets including JVM, JS, Native, and Wasm). Because it inherently risks throwing an exception,asis formally designated as the unsafe cast operator.
Smart Casting
A critical semantic feature of theas 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.
Nullability Constraints
Theas operator strictly enforces Kotlin’s nullability rules during the cast:
- Casting a
nullreference to a non-nullable type throws aNullPointerException. - To permit a
nullvalue to pass through the cast, the target type must be explicitly declared as nullable using the?suffix.
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.
Generics and Type Erasure
When usingas 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.
*), which casts to the base type while leaving the generic argument unknown.
Master Kotlin with Deep Grasping Methodology!Learn More





