kotlin
  1. kotlin-unsafe-and-safe-cast

Kotlin Unsafe and Safe Cast

Casting in Kotlin can be done in either an unsafe or safe manner. In this tutorial, we'll cover how to perform both types of casting.

Syntax

Unsafe Cast

val variable = object as ClassName

where variable is the object you want to cast and ClassName is the name of the target type.

Safe Cast

val variable = object as? ClassName

where variable is the object you want to cast and ClassName is the name of the target type.

Example

Unsafe Cast

val number: Any = 5
val result = number as String // This will cause a ClassCastException

Safe Cast

val number: Any = 5
val result = number as? String // This will return null

Explanation

Unsafe Cast

Unsafe casting is a way of casting an object to another type without checking if the object is actually of the target type. If an object is not of the target type and you try to cast it using an unsafe cast, a ClassCastException will be thrown.

Safe Cast

Safe casting is a way of casting an object to another type with a null check. If the object is not of the target type, null is returned instead of throwing an exception.

Use

Use an unsafe cast when you are certain that an object is of a certain type and you don't need to perform a null check. Use a safe cast when you are unsure if an object is of a certain type or if you want to avoid exceptions.

Important Points

  • Unsafe casting can cause a ClassCastException if an object is not actually of the target type.
  • Safe casting returns null instead of throwing an exception if an object is not actually of the target type.
  • Use unsafe casting only when you are certain an object is of a certain type and you don't need to perform a null check.

Summary

In this tutorial, we learned the difference between unsafe and safe casting in Kotlin. We covered the syntax, example, explanation, use, and important points of each type of casting. By understanding these concepts, you can make informed decisions about when to use each type of casting in your Kotlin code.

Published on: