johnny_crq
johnny_crq

Reputation: 4391

Kotlin Extension Function

Considering this:

MyView.setVisibility(View.VISIBLE)

can be simplified to this:

inline fun View.setVisible() = apply { visibility = View.VISIBLE }

MyView.setVisible()

Or this if you prefer:

inline infix fun View.vis(vis: Int) = apply { visibility = vis }
MyView vis View.VISIBLE

Is there anyway of accomplish the same by doing this:

MyView.VISIBLE

Upvotes: 2

Views: 679

Answers (2)

hotkey
hotkey

Reputation: 148179

Yes, you can write an extension property property with a getter like this:

val View.visible: View
    get() = apply { visibility = View.VISIBLE }

With the usage:

 myView.visible

However, keep in mind that properties with side effects in getters are generally discouraged (see also: Functions vs Properties), and this behavior is rather confusing for a property.

Upvotes: 2

mfulton26
mfulton26

Reputation: 31264

It seems a bit odd for a "getter" to modify state but you can use an extension property:

val View.VISIBLE: Unit
    get() {
        visibility = View.VISIBLE
    }

And you could also make it return the new visibility value or return itself so that you can potentially chain calls.

val View.VISIBLE: Int
    get() {
        visibility = View.VISIBLE
        return visibility
    }

or

val View.VISIBLE: View
    get() = apply { visibility = View.VISIBLE }

Upvotes: 5

Related Questions