data class Address(val city: String?, val zip: String?)
data class User(val name: String, val address: Address?)
fun main() {
val user: User? = User("Alice", Address("Austin", null))
// The whole chain short-circuits to null on any null link
val city: String? = user?.address?.city
println(city) // Austin
// Elvis: replace null with a default value
val display = user?.address?.city ?: "unknown"
println(display) // Austin
// Elvis with throw: fail fast if any link is null
fun requireCity(u: User?): String =
u?.address?.city ?: throw IllegalArgumentException("city required")
// Elvis with return: early-exit out of the enclosing function
fun describeOrBail(u: User?) {
val zip = u?.address?.zip ?: return // returns from describeOrBail
println("zip = $zip")
}
}
Create a free account and build your private vault. Share publicly whenever you want.