What is Type Casting in Kotlin: Simple Explanation and Examples
type casting means converting a variable from one type to another. It helps the program understand how to treat the data, using as for unsafe casting or as? for safe casting.How It Works
Type casting in Kotlin is like changing the label on a box so you know what is inside and how to use it. Imagine you have a box labeled 'Fruit' but inside is an apple. If you want to treat it specifically as an apple, you change the label to 'Apple'. This helps Kotlin understand the exact type you want to work with.
Kotlin uses two main ways to cast: as and as?. The as keyword tries to convert the type and throws an error if it fails, like trying to open a box expecting an apple but finding a shoe. The as? keyword tries to cast safely and returns null if it can't, so your program can handle the problem without crashing.
Example
This example shows how to cast an Any type to a String safely and unsafely.
fun main() {
val unknown: Any = "Hello Kotlin"
// Unsafe cast - throws exception if wrong type
val text1: String = unknown as String
println(text1)
// Safe cast - returns null if wrong type
val number: Any = 123
val text2: String? = number as? String
println(text2) // prints null
}When to Use
Use type casting when you have a variable with a general type but you know it holds a more specific type. For example, when working with collections of mixed types or APIs that return Any. Casting helps you access specific properties or functions of the actual type.
Safe casting (as?) is best when you are unsure if the cast will succeed, preventing crashes. Unsafe casting (as) is fine when you are certain about the type and want to catch errors early.
Key Points
- Type casting changes how Kotlin treats a variable's type.
asthrows an exception if casting fails.as?returnsnullif casting fails, avoiding crashes.- Use casting to access specific features of a variable's real type.
Key Takeaways
as for unsafe casting and as? for safe casting.Any.