kotlin-lazy

Delegated Properties

Source Doc: https://kotlinlang.org/docs/reference/delegated-properties.html

There are certain common kinds of properties, that, though we can implement them manually every time we need them, would be very nice to implement once and for all, and put into a library. Examples include

  • lazy properties: the value gets computed only upon first access,
  • observable properties: listeners get notified about changes to this property,
  • storing properties in a map, instead of a separate field for each property.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 代理属性 : Delegated Properties
* 关键字: by
* by lazy: 第一次调用的时候加载一次,第二次则直接返回值
*
* Delegates.observable 和 Delegates.vetoable 的区别在于
* vetoable 需要返回一个Boolean类型,当返回为false的时候,值并不会更改
*
* _, oldValue, newValue :_ 代表第一个参数不关心,默认是property类型
*
*/
class Lazy {
val boolean: Boolean by lazy {
println("function lazy")
false
}
var name: String by Delegates.observable("默认名字", {
_, oldValue, newValue ->
//实际项目中,这里可以在值有变化的时候做一次事情
println("old value : $oldValue ,new value $newValue")
})
var age: Int by Delegates.vetoable(0, {
property, oldValue, newValue ->
println("old value : $oldValue ,new value $newValue")
true //实际项目中,这里可以做一些逻辑判断
})
}
fun main(args: Array<String>) {
val lazy: Lazy = Lazy()
println("第一次调用 lazy.boolean")
lazy.boolean
println("第二次调用 lazy.boolean")
lazy.boolean
println("直接调用 lazy.name 的值: ${lazy.name}")
lazy.name = "更改过后的名字"
println("更改了lazy.name 的值: ${lazy.name}")
}