Home > front end >  Is it necessary in Kotlin to specify that a condition be other than null, if it is already specified
Is it necessary in Kotlin to specify that a condition be other than null, if it is already specified

Time:10-14

In the following code snippet, could you spare me the "chargesVO != null" in the conditions, since I specify them to be either above zero or below zero values?

@BindingAdapter("binding:returnChargesLabel")
@JvmStatic
fun setReturnChargesLabel(textView: TextView, chargesVO: ReturnSummaryChargesVO?) {
  textView.isVisible = chargesVO != null

  when {
    chargesVO != null && chargesVO.amount >= 0.toString() -> {
      textView.text = chargesVO.label
    }
    chargesVO != null && chargesVO.amount < 0.toString() -> {
      textView.text = "0"
    }
  }
}

CodePudding user response:

You never assert anywhere that chargesVO isn't null, so you need those checks before using it. You could add a single let check before using it though, like this:

chargesVO?.let {
  val amt = it.amount.coerceAtLeast(0.0)
  textView.text = "$amt"
}

Or just return if it's null, then you can safely use it after the check

if( chargesVO == null ) return

val amt = chargesVO.amount.coerceAtLeast(0.0)
textView.text = "$amt"

Note that I simplified the when here since you just want to print 0 if the value is < 0 - you can just coerce the value to be at least 0 with the coerceAtLeast method

  • Related