Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

Safe null access


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 
            } 
          } 
        } 
      } 
      return...