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

Properties or methods?


Properties are very similar to methods; you end up with a getter/setter method under the hood as you have already seen. However, methods and properties have different usage patterns. You should view properties as fields on steroids. While they look like fields, the syntax for a property looks like we deal with a field; properties provide the flexibility of methods.

A class method represents an action, while a property represents data. Properties should be used like a field and not like an action or behavior. When you want to design your type and define one or more properties, follow these guidelines to decide whether it is suitable to do so:

  1. Avoid having complex code in the getter code body. A caller expects a fast return. Definitely, do not connect to a database or do a rest call from the property's getter code base.

  2. Getting a property should not cause any side-effects; avoid even throwing exceptions from the getter's code.

  3. Mark your setter as private/protected if you...