Smart casts are a very nice feature and offer a readable way to do branching when dealing with nulls. However, when we have chained operations, and each step may produce a null, the code quickly becomes unreadable.
Consider the following snippet:
class Person(name: String, val address: Address?)
class Address(name: String, postcode: String, val city: City?)
class City(name: String, val country: Country?)
class Country(val name: String)
fun getCountryName(person: Person?): String? {
var countryName: String? = null
if (person != null) {
val address = person.address
if (address != null) {
val city = address.city
if (city != null) {
val country = city.country
if (country != null) {
countryName = country.name
}
}
...