2

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
johnny_crq
  • 4,291
  • 5
  • 39
  • 64

2 Answers2

5

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 }
mfulton26
  • 29,956
  • 6
  • 64
  • 88
2

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.

hotkey
  • 140,743
  • 39
  • 371
  • 326