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

Lateinit versus lazy


At first, lateinit var and by lazy {...} sound quite similar. However, there are significant differences between the two of them:

  1. The lazy {...} delegate can only be used for val properties; lateinit can only be used for var properties.

  2. A lateinit var property can't be compiled into a final field, hence you can't achieve immutability.

  3. A lateinit var property has a backing field to store the value, whereas lazy {...} creates a delegate object that acts as a container for the value once created and provides a getter for the property. If you need the backing field to be present in the class, you will have to use lateinit.

  4. The lateinit property cannot be used for nullable properties or Java primitive types. This is a restriction imposed by the usage of null for uninitialized values.

  5. The lateinit var property is more flexible when it comes to where it can be initialized. You can set it up anywhere the object is visible from. For lazy{}, it defines the only initializer for the...