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 ...