0
0
KotlinHow-ToBeginner · 3 min read

How to Use the as Keyword in Kotlin: Syntax and Examples

In Kotlin, the as keyword is used to cast an object to a specific type. It attempts to convert the object to the given type and throws an exception if the cast is not possible. You can also use as? for a safe cast that returns null instead of throwing an error.
📐

Syntax

The as keyword is used to cast an object to a specific type. The syntax is:

  • val variable = expression as Type - casts expression to Type and throws an exception if it fails.
  • val variable = expression as? Type - safe cast that returns null if the cast is not possible.
kotlin
val obj: Any = "Hello"
val str: String = obj as String

val num: Any = 123
val strSafe: String? = num as? String
💻

Example

This example shows how to use as for casting and as? for safe casting to avoid exceptions.

kotlin
fun main() {
    val anyValue: Any = "Kotlin"

    // Unsafe cast - will succeed
    val str1: String = anyValue as String
    println(str1)  // Output: Kotlin

    val numberValue: Any = 42

    // Unsafe cast - will throw ClassCastException
    // val str2: String = numberValue as String  // Uncommenting this line causes an error

    // Safe cast - returns null instead of exception
    val str3: String? = numberValue as? String
    println(str3)  // Output: null
}
Output
Kotlin null
⚠️

Common Pitfalls

Using as without ensuring the object is of the target type can cause a ClassCastException. Always use as? if you are unsure about the type to avoid runtime crashes.

Example of wrong and right usage:

kotlin
fun main() {
    val anyValue: Any = 100

    // Wrong: unsafe cast causes exception
    // val str: String = anyValue as String  // Throws ClassCastException

    // Right: safe cast returns null
    val safeStr: String? = anyValue as? String
    println(safeStr)  // Output: null
}
Output
null
📊

Quick Reference

KeywordDescriptionBehavior on Failure
asCasts an object to a specified typeThrows ClassCastException if cast fails
as?Safe cast to a specified typeReturns null if cast fails

Key Takeaways

Use as to cast an object when you are sure of its type.
Use as? for safe casting to avoid exceptions and get null on failure.
Avoid unsafe casts to prevent runtime crashes from ClassCastException.
Remember that as throws an exception if the cast is invalid.
Safe casts help write more robust and error-resistant Kotlin code.