1. Overview
In this article, we will discuss the as keyword in kotlin with few examples.
2. Unsafe cast as operator
Suppose you want to convert a data type into another data type manually, you can use this cast operator as
. Let’s take an example. Here, we have BaseClass
, DerivedClass
which extends the BaseClass
, HelperClass
that depends on the aforementioned classes.
In main()
function, we send the instance of DerivedClass to the HelperClass
constructor. Inside the HelperClass help()
function, we had to access the DerivedClass
calculate
function. Since the instance passed is of type BaseClass
, we had to use as
keyword to cast baseClass
instance to DerivedClass
instance.
fun main() { val derivedClass = DerivedClass() val helperClass = HelperClass(derivedClass) helperClass.help() } class HelperClass(private val baseClass: BaseClass) { val derivedClass : DerivedClass = baseClass as DerivedClass fun help() { derivedClass.print() println(derivedClass.calculate(5, 4)) } } open class BaseClass() { open fun print() { println("BaseClass") } } class DerivedClass : BaseClass() { override fun print() { println("DerivedClass") } fun calculate(a: Int, b: Int) : Int { return a*b } }
Result:
DerivedClass 20
This as
keyword is an unsafe cast operator and throws an exception if the casting is not workable. Let’s take another example to understand. We have declared another class IndependentClass which is not a subclass of any class. If we try to cast IndependentClass
instance as BaseClass
, the as
casting operator throws an exception.
fun main() { val derivedClass = DerivedClass() val helperClass = HelperClass(derivedClass) helperClass.help() } class HelperClass(private val baseClass: BaseClass) { val derivedClass : IndependentClass = baseClass as IndependentClass fun help() { derivedClass.print() println(derivedClass.calculate(5, 4)) } } class IndependentClass() { fun print() { println("IndependentClass") } fun calculate(a: Int, b: Int) : Int { return a+b } } open class BaseClass() { open fun print() { println("BaseClass") } } class DerivedClass : BaseClass() { override fun print() { println("DerivedClass") } fun calculate(a: Int, b: Int) : Int { return a*b } }
Result:
Exception in thread “main” java.lang.ClassCastException: DerivedClass cannot be cast to IndependentClass
Suppose you like to cast a variable as String and if that variable is null, it throws the exception.
val x: String = y as String
To make such code correct for null values, use the nullable type on the right-hand side of the cast (String?). This will prevent the exception.
val x: String? = y as String?