Safe Cast Operator (as?) in Kotlin
On this page (12sections)
Introduction
Safe Cast Operator (as?) is a fundamental concept every Kotlin developer should understand. Null safety is one of Kotlin’s signature features. It catches null-related bugs at compile time instead of crashing at runtime with a NullPointerException.
The safe cast operator as? tries to cast a value to another type. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- The safe cast operator as? tries to cast a value to another type.
- If the cast fails, it returns null instead of throwing ClassCastException.
- It is useful when you are not sure about the runtime type of a value.
Syntax
val result = value as? TargetType
Safe Cast Operator (as?) in Kotlin Example Program in Kotlin
fun main(args: Array<String>) {
val value: Any = "Little Drops"
val text = value as? String
val number = value as? Int
println("Text: $text")
println("Number: $number")
}
Sample Output
Text: Little Drops
Number: null
When to use
Use nullable types when a value may legitimately be absent — optional fields, parsed input, or database lookups that can miss.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
val value: Any = "Little Drops"assigns or updates a value used later in the program. -
val text = value as? Stringassigns or updates a value used later in the program. -
val number = value as? Intassigns or updates a value used later in the program. -
The
println("Text: $text")statement writes a line to the console — this produces part of the sample output below. -
The
println("Number: $number")statement writes a line to the console — this produces part of the sample output below. -
The safe cast operator as? tries to cast a value to another type.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
- Prefer non-nullable types by default; add
?only when null is a valid state. - Use safe call (
?.) and Elvis (?:) instead of force unwrap (!!) unless you are certain. - Handle nullable collections and nested properties with
?.chains orletblocks.
Common Mistakes
- Using
!!everywhere instead of handling null safely — this reintroduces NPE risk. - Forgetting that platform types from Java are implicitly nullable.
- Comparing nullable strings with
==without considering both sides may be null.
Key Points
- The safe cast operator as? tries to cast a value to another type.
- If the cast fails, it returns null instead of throwing ClassCastException.
- It is useful when you are not sure about the runtime type of a value.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.
Frequently Asked Questions
What is Safe Cast Operator (as?) in Kotlin?
When should I use Safe Cast Operator (as?)?
How is Safe Cast Operator (as?) different from Java?
How do I practice this topic?
Related Tutorials
Nullable Types in Kotlin
Learn Nullable Types in Kotlin with clear explanation, syntax, example program, sample output, best practices, and FAQs.
Read tutoriallet Function for Null Safety in Kotlin
Learn let Function for Null Safety in Kotlin with clear explanation, syntax, example program, sample output, best practices, and FAQs.
Read tutorial