Properties and Fields

Properties and Fields

Declaring Properties

Classes in Kotlin can have properties. These can be declared as mutable, using the var keyword or read-only using the val keyword.

class Address {
    var name: String = ...
    var street: String = ...
    var city: String = ...
    var state: String? = ...
    var zip: String = ...
}

To use a property, we simply refer to it by name, as if it were a field in Java:

fun copyAddress(address: Address): Address {
    val result = Address() // there's no 'new' keyword in Kotlin
    result.name = address.name // accessors are called
    result.street = address.street
    // ...
    return result
}

Getters and Setters

The full syntax for declaring a property is

var <propertyName