How to access class members with same name in extension function in Kotlin android

1.7k views Asked by At

i'm new to kotlin for android. and i want to access class member that having same name in extension function. for example:

   var visibility = null //class level variable

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

how can i access visibility in changeVisibleState method.

2

There are 2 answers

0
s1m0nw1 On BEST ANSWER

With a qualified this this@Hello you can access Hello's property instead of 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
        [email protected] = 12
    }
}
0
Bhuvanesh BS On

You can use this operator.

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

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