Properties

Declaring Properties

Properties in Kotlin classes can be declared either as mutable using the var keyword, or as read-only using the val keyword.

  1. class Address {
  2. var name: String = "Holmes, Sherlock"
  3. var street: String = "Baker"
  4. var city: String = "London"
  5. var state: String? = null
  6. var zip: String = "123456"
  7. }

To use a property, simply refer to it by name:

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

Getters and Setters

The full syntax for declaring a property is

  1. var <propertyName>[: <PropertyType>] [= <property_initializer>]
  2. [<getter>]
  3. [<setter>]

The initializer, getter and setter are optional. Property type is optional if it can be inferred from the initializer (or from the getter return type, as shown below).

Examples:

  1. var allByDefault: Int? // error: explicit initializer required, default getter and setter implied
  2. var initialized = 1 // has type Int, default getter and setter

The full syntax of a read-only property declaration differs from a mutable one in two ways: it starts with val instead of var and does not allow a setter:

  1. val simple: Int? // has type Int, default getter, must be initialized in constructor
  2. val inferredType = 1 // has type Int and a default getter

We can define custom accessors for a property. If we define a custom getter, it will be called every time we access the property (this allows us to implement a computed property). Here’s an example of a custom getter:

  1. val isEmpty: Boolean
  2. get() = this.size == 0

If we define a custom setter, it will be called every time we assign a value to the property. A custom setter looks like this:

  1. var stringRepresentation: String
  2. get() = this.toString()
  3. set(value) {
  4. setDataFromString(value) // parses the string and assigns values to other properties
  5. }

By convention, the name of the setter parameter is value, but you can choose a different name if you prefer.

Since Kotlin 1.1, you can omit the property type if it can be inferred from the getter:

  1. val isEmpty get() = this.size == 0 // has type Boolean

If you need to change the visibility of an accessor or to annotate it, but don’t need to change the default implementation, you can define the accessor without defining its body:

  1. var setterVisibility: String = "abc"
  2. private set // the setter is private and has the default implementation
  3. var setterWithAnnotation: Any? = null
  4. @Inject set // annotate the setter with Inject

Backing Fields

In Kotlin, a field is only used when needed as part of a property to hold its value in memory. Fields can not be declared directly. However, when a property needs a backing field, Kotlin provides it automatically. This backing field can be referenced in the accessors using the field identifier:

  1. var counter = 0 // Note: the initializer assigns the backing field directly
  2. set(value) {
  3. if (value >= 0) field = value
  4. }

The field identifier can only be used in the accessors of the property.

A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier.

For example, in the following case there will be no backing field:

  1. val isEmpty: Boolean
  2. get() = this.size == 0

Backing Properties

If you want to do something that does not fit into this “implicit backing field” scheme, you can always fall back to having a backing property:

  1. private var _table: Map<String, Int>? = null
  2. public val table: Map<String, Int>
  3. get() {
  4. if (_table == null) {
  5. _table = HashMap() // Type parameters are inferred
  6. }
  7. return _table ?: throw AssertionError("Set to null by another thread")
  8. }

On the JVM: The access to private properties with default getters and setters is optimized so no function call overhead is introduced in this case.

Compile-Time Constants

If the value of a read-only property is known at the compile time, mark it as a compile time constant using the const modifier. Such properties need to fulfil the following requirements:

Such properties can be used in annotations:

  1. const val SUBSYSTEM_DEPRECATED: String = "This subsystem is deprecated"
  2. @Deprecated(SUBSYSTEM_DEPRECATED) fun foo() { ... }

Late-Initialized Properties and Variables

Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.

To handle this case, you can mark the property with the lateinit modifier:

  1. public class MyTest {
  2. lateinit var subject: TestSubject
  3. @SetUp fun setup() {
  4. subject = TestSubject()
  5. }
  6. @Test fun test() {
  7. subject.method() // dereference directly
  8. }
  9. }

The modifier can be used on var properties declared inside the body of a class (not in the primary constructor, and only when the property does not have a custom getter or setter) and, since Kotlin 1.2, for top-level properties and local variables. The type of the property or variable must be non-null, and it must not be a primitive type.

Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn’t been initialized.

Checking whether a lateinit var is initialized (since 1.2)

To check whether a lateinit var has already been initialized, use .isInitialized on the reference to that property:

  1. if (foo::bar.isInitialized) {
  2. println(foo.bar)
  3. }

This check is only available for the properties that are lexically accessible, i.e. declared in the same type or in one of the outer types, or at top level in the same file.

Overriding Properties

See Overriding Properties

Delegated Properties

The most common kind of properties simply reads from (and maybe writes to) a backing field. On the other hand, with custom getters and setters one can implement any behaviour of a property. Somewhere in between, there are certain common patterns of how a property may work. A few examples: lazy values, reading from a map by a given key, accessing a database, notifying listener on access, etc.

Such common behaviours can be implemented as libraries using delegated properties.