Search code examples
androidkotlinextension-function

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

Solution

  • 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 }