kotlinproperty

kotlin property

属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//class中默认为private,即使加了public也没用,并自动生成getter,setter
var <propertyName>: <PropertyType> [= <property_initializer>]
[private] [<getter>]
[private] [<setter>]
// Demo
class Addr {
var age: String? = null
var name: String? = null
get() = name
set(value) {
// 实际是调用set,会造成死循环,用field代替当前属性
field = "$value-from_set"
println(field)}
}

常量

1
2
//这个只能放伴生对象
const val <propertyName>: <PropertyType> [= <property_initializer>]

延迟初始化

1
2
3
4
5
6
7
//private
var name2 : String? = null
//public
lateinit var name:String
val lazyValue: String by lazy {
"lazyValue"
}

[自欺欺人的属性覆盖]->

委托属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Example {
var p: String by Delegate()
}
class Delegate {
var pro : String = ""
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return pro
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
pro = value
}
}

可观察属性

1
2
3
4
5
class Change{
var change : String by Delegates.observable("init"){
property, oldValue, newValue -> println("${property.visibility}-$oldValue,$newValue")
}
}

map映射

1
2
3
4
5
6
7
8
9
10
fun main(args: Array<String>) {
var user = MutableUser(mutableMapOf("name" to "test", "age" to 1))
println(user.name)
println(user.age)
}
class MutableUser(val map: MutableMap<String, Any?>) {
var name: String by map
var age: Int by map
}

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器