kotlin when interface‘s field set/get

kotlin  when interface's field set/get 

interface Listener {
    var num: Int
    fun number(n: Int)
}

class MyListener : Listener {
    override var num: Int = -1
        get() = field
        set(value) {
            field = value
        }

    override fun number(n: Int) {
        num = n
    }
}

fun main(args: Array) {
    var l1 = MyListener()
    l1.number(1)

    var l2 = MyListener()
    l2.number(2)

    var ls = ArrayList()
    ls.add(l1)
    ls.add(l2)

    for (l in ls) {
        when (l) {
            l1 -> {
                println("l1->{${l1.num}}")
            }

            l2 -> {
                println("l2->{${l2.num}}")
            }

            else -> {
                println("else->${l.num}")
            }
        }
    }
}

 

l1->{1}
l2->{2}

 

 

kotlin类成员变量字段field的get/set_zhangphil的博客-CSDN博客kotlin类成员变量字段field的get/set。https://blog.csdn.net/zhangphil/article/details/129233934

 

你可能感兴趣的:(kotlin,kotlin)