var
val
1 2 3
| var <propertyName>[: <PeopertyType>] [= <property_initializer>] [<getter>] [<setter>]
|
1 2 3
| var example: String get() ... set(value) {...}
|
幕后字段
:(还有幕后属性,起了个临时变量的作用吧?)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package app.classes
class BackingFields { var counter = 0 set(value) { if (value >= 0) field = value } }
fun main() { var backingFields = BackingFields() println("backingFields.counter = ${backingFields.counter}") backingFields.counter = 1 println("backingFields.counter = ${backingFields.counter}") var backingFields2 = BackingFields() backingFields2.counter = -1 println("backingFields.counter = ${backingFields2.counter}") }
|
1 2 3
| backingFields.counter = 0 backingFields.counter = 1 backingFields.counter = 0
|