user3806331 user3806331 - 10 months ago 41
Android Question

Kotlin Extension Function

Considering this:


can be simplified to this:

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


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:



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


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