美文网首页
Kotlin---observable、map

Kotlin---observable、map

作者: lewis2017 | 来源:发表于2018-10-30 16:31 被阅读0次

1、observable观察属性变化,相当于,每次属性被赋值(初始化也算一次赋值)例如:


首先,需要导入 Delegates类,
import kotlin.properties.Delegates

class User {

    var name: String by Delegates.observable("<no name>") {

        prop, old, new ->

        println("$old -> $new")

    }

}

fun main(args: Array<String>) {

    val user = User()

    user.name = "first"

    user.name = "second"

}

结果:

<no name> -> first

first -> second

2、map操作,其实是调用Delegates.mapVal()方法, 拥有一个 map 实例并返回一个可以从 map 中读其中属性的代理。在应用中有很多这样的例子,比如解析 JSON 或者做其它的一些 “动态”的事情

class User(val map: Map<String, Any?>) {

val name: String by Delegates.mapVal(map)

val age: Int    by Delegates.mapVal(map)

}

调用:

val user = User(mapOf (

        "name" to "John Doe",

         "age" to 25

))

相关文章

网友评论

      本文标题:Kotlin---observable、map

      本文链接:https://www.haomeiwen.com/subject/ybigtqtx.html