Objective: Minimize Nulls
Despite all of these things, null
still winds up being a pain. To a degree, that is intentional. By making working with null
annoying, the Kotlin language designers are trying to steer you to minimize your use of null
values. Yet, at the same time, you can still work with libraries and frameworks for which null
is a possibility (e.g., Java libraries used by Kotlin/JVM projects).
In particular, one common use of null
that you can try to eliminate is using it as some “magic” or default value. In classic programming, we often use null
to signify “we do not have this value yet” or “there is no value for this property”. In Kotlin, we can use things like sealed classes to avoid the null
. So, instead of:
data class Customer(val name: String)
data class Order(val customer: Customer? = null)
val order = Order()
…you could have:
sealed class OrderingEntity {
data class Customer(val name: String) : OrderingEntity()
object Unassigned : OrderingEntity()
}
data class Order(val customer: OrderingEntity = OrderingEntity.Unassigned)
val order = Order()
This is somewhat more verbose. However, it more correctly models the situation (we do not have a customer yet, so it is unassigned). And, we avoid any possible NullPointerException
or having to deal with lots of ?.
or ?:
and the like to make use of the customer
property.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.