1.1.50.8. fejezet, Tulajdonságok

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

Getter és setter

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

Példa:

class Rectangle(val width: Int, val height: Int) {
    val area: Int // property type is optional since it can be inferred from the getter's return type
        get() = this.width * this.height
}
 
var stringRepresentation: String
    get() = this.toString()
    set(value) {
        setDataFromString(value) // parses the string and assigns values to other properties
    }

Háttér mező

A setter-ben a filed azonosítóval lehet írni a tulajdonságot:

var counter = 0 // the initializer assigns the backing field directly
    set(value) {
        if (value >= 0)
            field = value
            // counter = value // ERROR StackOverflow: Using actual name 'counter' would make setter recursive
    }

Háttér tulajdonság

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

Fordítás idejű konstans

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

Kései inicializálású tulajdonságok és változók

public class MyTest {
    lateinit var subject: TestSubject
 
    @SetUp fun setup() {
        subject = TestSubject()
    }
 
    @Test fun test() {
        subject.method()  // dereference directly
    }
}

Ellenőrizni lehet az inicializálást:

if (foo::bar.isInitialized) {
    println(foo.bar)
}