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

Syntax and variations


The syntax for declaring a property is as follows:

    var/val<propertyName>:<PropertyType>[=<property_initializer>] 
      [<getter>] 
      [<setter>] 

Both the initializer and the setter parts are optional. Furthermore, the property type can also be left out since the compiler can infer it, thus saving you keystrokes. However, for code clarity, it is advisable to add the property type.

If you define a read-only property by using the val keyword, you only have the getter and no setter. Imagine you have to define a class hierarchy for a drawing application. You would want a property for the area. Following is a typical implementation for such property when it comes to a Rectangle class:

    interface Shape {
      val Area: Double
      get;
    }

    class Rectangle(val width: Double, val height: Double) : Shape {
      override val Area: Double
      get() = width * height

 ...