-2

I have following code:

 private fun setCashPaymentContainer(isSelected: Boolean) {      
        if (isSelected) {
            dataBinding.cashPaymentCheckImageViewContainer.visibility = View.VISIBLE
        } else {
            dataBinding.cashPaymentCheckImageViewContainer.visibility = View.GONE
        }
    }

It works fine, but I would like to improve it and write it as simplified and readable if else block.It would be nice if I can make a one line if else statement Please suggest.

Hardik Trivedi
  • 5,677
  • 5
  • 31
  • 51
Alexei
  • 14,350
  • 37
  • 121
  • 240
  • yeah why would that not be possible? – Tim Oct 31 '19 at 15:06
  • 3
    Does this answer your question? [Kotlin Ternary Conditional Operator](https://stackoverflow.com/questions/16336500/kotlin-ternary-conditional-operator) – Meg Oct 31 '19 at 15:06
  • 1
    From context I assume this is Android. If you're including `Android KTX` in your project there's extension property available you can already use: [`View.isVisible`](https://developer.android.com/reference/kotlin/androidx/core/view/package-summary#(android.view.View).isVisible:kotlin.Boolean) so you can simply do `view.isVisible = isSelected`. – Pawel Oct 31 '19 at 16:36

2 Answers2

5

You can use an if expression:

dataBinding.cashPaymentCheckImageViewContainer.visibility = if(isSelected) View.VISIBLE else View.GONE

...however in this case, isVisible is better (credit: Pawel):

dataBinding.cashPaymentCheckImageViewContainer.isVisible = isSelected

Note: There are also isInvisible and isGone.

charles-allen
  • 3,891
  • 2
  • 23
  • 35
2

Indeed, Kotlin allows this.

private fun setCashPaymentContainer(isSelected: Boolean) {      
    dataBinding.cashPaymentCheckImageViewContainer.visibility = when {
        isSelected -> View.VISIBLE
        else -> View.GONE
    }
}

You can actually make it even nicer (imo):

inline fun View.showIf(condition: (View) -> Boolean) {
    val shouldShow = condition(this) 

    this.visibility = when {
        shouldShow -> View.VISIBLE
        else -> View.GONE
    }
}

Now you can do

private fun setCashPaymentContainer(isSelected: Boolean) {      
    dataBinding.cashPaymentCheckImageViewContainer.showIf { isSelected }
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428