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 the safe cast operator. It attempts to cast an expression to a specified target type at runtime. If the runtime type of the expression is not compatible with the target type, it returns null instead of throwing a ClassCastException.
val result: TargetType? = expression as? TargetType

Mechanics and Behavior

  • Runtime Type Evaluation: The operator evaluates the actual runtime instance of the left-hand operand (expression).
  • Type Compatibility: If the instance is exactly TargetType or a valid subtype of TargetType, the cast succeeds, and the value is returned as the target type.
  • Null Yielding: If the instance is structurally incompatible with the target type, the operation evaluates to null. Because of this failure state, the resulting type of an as? expression is inherently forced to be a nullable type (TargetType?), even if the right-hand operand specifies a non-nullable type.
  • Null Operands: If the left-hand expression evaluates to null, the as? operator will safely return null without attempting the cast.

Contrast with Unsafe Cast (as)

The standard cast operator (as) is considered “unsafe” because it strictly enforces the type contract at runtime, resulting in an exception upon failure:
// Throws ClassCastException if expression is not compatible with TargetType
val unsafe: TargetType = expression as TargetType 
The as? operator acts as a structural safeguard against this exception, transforming a potential runtime crash into a standard Kotlin nullability state:
// Returns null if expression is not compatible with TargetType
val safe: TargetType? = expression as? TargetType 

Type Erasure Considerations

Due to type erasure on the JVM, casting to generic types with as? can result in unchecked cast warnings. At runtime, generic type arguments are erased, meaning as? can only verify the base class, not the generic parameters.
// The compiler cannot guarantee the list contains Strings at runtime.
// It only verifies that 'expression' is a List.
val safeList = expression as? List<String> 
Master Kotlin with Deep Grasping Methodology!Learn More