given code below, why kotlin enforce you to do nested null check , like bellow printCountry function it has 4 null checks with “?.” when just first check is really needed?
fun printCountry(person: Person?) {
println(person?.address?.city?.country?.name ?: “Unknown Country”)
}
data class Country(
val name: String,
val isoCode: String
)
data class City(
val name: String,
val state: String,
val country: Country
)
data class Address(
val street: String,
val number: String,
val postalCode: String,
val city: City
)
data class Person(
val name: String,
val age: Int,
val address: Address
)
I hope it is clear why this happens: On every level, the input may be null, and you have to deal with it somehow.
If you are annoyed by the question marks, you can always write something like person?.apply{address.city.country.name} ?: "Unknown Country" or longer, but easier to understand if (person != null) person.address.city.country.name else "Unknown Country"
If you really hate it, how about this:
fun <T, R> T?.whenNull(default: R, body: T.()-> R): R =
if (this == null) default else body(this)
println(person.whenNull("Unknown Country") { address.city.country.name })