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

A non-null property delegate


The Kotlin framework is quite rich; it provides support for a delegated property for non-null values. All you have to do is use Delegates.nonNull, like in this simple example:

    class NonNullProp { 
      var value: String by Delegates.notNull<String>() 
    } 
 
    val nonNull = NonNullProp() 
    nonNull.value = "Kotlin rocks" 
    println("Non null value is: ${nonNull.value}") 
 
    //this will not compile 
    nonNull.value = null

Trying to access the property value before it has been initialized would lead to an IllegalStateException being raised. Furthermore, if you try to set a null to it, you will get a compilation error.