Nullable Types and Casts
When it comes to casts and nullable types, you can use the nullable form of as
(as?
):
val nullableList : MutableList<String>? = mutableListOf()
nullableList?.add("this is not null")
nullableList?.add("this is also not null")
val simplerList = nullableList as? List<String>
println(simplerList)
In this case, simplerList
winds up being a List?
of String
objects. If the object being cast is null
, you wind up with a null
value.
as?
is also useful for cases where the object might not be of the desired type:
open class Animal
class Frog : Animal()
class Axolotl : Animal()
fun main() {
val kermit : Animal = Frog()
val notAnAxolotl = kermit as? Axolotl
println(notAnAxolotl)
}
as?
results in a null
value if either:
- The object being cast itself is
null
, or - The object being cast is not of the type that you are trying to cast it to
In this case, kermit
is not an Axolotl
. As a result, notAnAxolotl
winds up being null
, with the variable being typed as Axolotl?
.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.