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

Nullable types


Kotlin's type system is advanced enough that it can track the difference between nullable types and non-nullable types. When we define a variable in Kotlin, as we have been doing so far, we cannot assign a null to it. This code, for instance, would not compile:

    val name: String = null // does not compile 

Assigning null to a var will not compile either:

    var name: String = "harry" 
    name = null // does not compile 

To inform the Kotlin compiler that we will allow a variable to contain a null, we must suffix the type with a ?:

    val name: String? = null 
    var name: String? = "harry" 
    name = null 

Both the preceding snippets will now compile.

Similarly, we can return nullable and non-nullable types from a function, use them as function parameters, and so on:

    fun name1(): String = ... 
 
    fun name2(): String? = ... 

The name1 function cannot return a null reference. The name2 function may or may not. If we were...