2

我是 kotlin for android 的新手。我想访问在扩展函数中具有相同名称的类成员。例如:

   var visibility = null //class level variable

    //EXTENSION FUNCTION
    fun ProgressBar.changeVisibleState(flag: Boolean) {
        if (flag)
            visibility = View.VISIBLE
        else
            visibility = View.INVISIBLE
    }

我如何访问方法visibilitychangeVisibleState

4

2 回答 2

2

您可以使用this运算符。

class Hello {
    var visibility: Int = 0 //class level variable

    //EXTENSION FUNCTION
    fun ProgressBar.changeVisibleState(flag: Boolean) {
        if (flag)
            this@Hello.visibility = View.VISIBLE
        else
            this@Hello.visibility = View.INVISIBLE
    }
}
于 2017-09-07T10:36:39.317 回答
2

使用合格的 this this@Hello您可以访问Hello' 属性而不是ProgressBar's。

class Bye {
    var visibility: Int = 0 //class level variable
}
class Hello {
    var visibility: Int = 0 //class level variable

    fun Bye.changeVisibleState(flag: Boolean) {
        //access Bye's prop
        visibility = if (flag) 1 else 2
        //access Hello's prop
        this@Hello.visibility = 12
    }
}
于 2017-09-07T11:22:51.433 回答