Type Casting in Kotlin

Learn via video courses
Topics Covered

Overview

The ability to change one data type into another is an essential feature of object-oriented programming languages. To facilitate this feature, these languages introduced the concept of type casting.

Type casting is the process of converting a specific data type into a larger or smaller data type. However, this complex change may result in failures or unexpected outcomes. To overcome such situations, Kotlin introduces two operators that offer you the tools you need to manage type casting: the safe and unsafe operators.

Introduction

Type casting in Kotlin refers to the process of explicitly converting a value from one data type to another. Type casting is usually accomplished by the use of some operators or specific syntax. Sometimes, the interpreter or compiler can accomplish it automatically behind the scenes. The conversion of an integer to a string is an example of a typecast operation.

It is important to understand that type casting is a delicate procedure that must be approached with prudential behavior. Type casting without proper consideration might result in exceptions and significant errors. Hence, it's crucial to clearly understand how to employ type casting correctly, comprehend their anticipated outcomes, and be equipped to avert or manage errors that might arise.

Note:

  • Downcasting is the process of converting a type to a smaller type. A smaller type takes up fewer bytes in memory or is a descendant of the current type in an inheritance structure.
  • Upcasting refers to the process of changing a type to a larger type. A more significant type takes up more memory or indicates the current type's parent in an inheritance tree.

Explicit Type Casting in Kotlin

In many programming languages, including Kotlin, there are situations where you need to convert data from one type to another explicitly. This could be because you want to perform operations that require values of a specific type or because you want to store a value in a variable of a different type. To overcome such situations, we use explicit type casting in Kotlin.

Explicit type casting is the deliberate and manual process of converting a value from one data type to another. This is done explicitly by the programmer using specific language constructs or functions provided by the programming language.

Explicit type casting can be accomplished by using the following:

Unsafe Cast Operator (as)

The unsafe cast operator in Kotlin is denoted by the keyword as. This casting method is used when you are convinced that the given object can be cast safely to the target type. A ClassCastException will be thrown at runtime if the cast is not possible.

Syntax

Here, variable is the value to be cast, and TargetType is the type in which it will be cast. If the cast is valid and possible, the result will be of the TargetType. If the cast cannot be completed (for example, because the object is not an instance of TargetType), a ClassCastException is thrown at runtime.

Example

Let's consider a simple program to understand the working of unsafe cast operator (as).

In the above example, the variable str1 is of type Any, but its actual value is a String. The unsafe cast operator as is explicitly used to cast str1 to the other String variable str2. Since the cast is valid in this case, the program runs successfully and prints the following

Output.

Let's take another example in which we try to attempt an unsafe cast that is not valid, a ClassCastException will occur:

As str1 contains an Int in this scenario, attempting to cast it to a String with the unsafe cast operator will result in a ClassCastException.

Similarly, when nullable types are involved, the as cast operator may fail, as shown in the following program:

In this example, we are attempting to convert a nullable type to a non-nullable type. This would result in the error null cannot be cast to non-null type kotlin.String. To avoid this, specify str2 as a nullable type, as seen below:

The program will execute successfully and prints the output:

Safe Cast Operator (as?)

The safe cast operator in Kotlin is denoted by the keyword as?. This type of casting is used when you want to cast an object to a specified type but are uncertain if the casting will succeed. If the object can be securely cast to the target type, the result will be of that type; otherwise, it will be null. This helps to avoid runtime exceptions.

Syntax

Here, variable is the value to be cast, and TargetType is the type in which it will be cast. If the cast is valid and possible, the result will be of the TargetType. If the cast cannot be completed the result will be null.

Example

Let's take a simple program to understand the working of unsafe cast operator (as).

In the above example, the variable str1 is of type Any, but its actual value is a String. The safe cast operator as? is explicitly used to cast str1 to the other String variable str2. Since the cast is valid in this case, the program runs successfully and prints the following

Output

Let's take another example in which we try to attempt an safe cast that is not valid.

As str1 contains an Int in this scenario, attempting to cast it to a String with the safe cast operator then program will simply return null.

as vs is in Kotlin

as operator

  • The as operator is used to cast types explicitly. It tries to cast an expression to a specified type.

  • Syntax:

  • If the cast is valid and possible, the result will be of the TargetType.

  • If the cast cannot be completed, a ClassCastException is thrown at runtime.

  • The example of the as operator is:

is operator

  • The is operator is used for type checking. It determines whether an expression is an instance of the given type.

  • Syntax:

  • If the expression is an instance of the specified type, the is operator returns true; otherwise, it returns false.

  • It can be used to conditionally perform actions based on the type of expression without actually casting it.

  • The example of the is operator is:

Conclusion

  • Type casting in Kotlin refers to explicitly converting a value from one data type to another.
  • Explicit type casting is the deliberate and manual process of converting a value from one data type to another.
  • It's important to be cautious when using the unsafe cast operator as to avoid runtime exceptions. If you're unsure about the compatibility of types, you might consider using the safe cast operator as? or performing type checks with the is operator before attempting an unsafe cast.
  • The is operator is used for type checking. It determines whether an expression is an instance of the given type.