Can I always merge two conditions into one row in Kotlin?

The Code A is good, I hope to optimize it, so I write the Code B.

I'm not sure whether the Code B is always correct.

It will be OK if Kotlin check clipboard.hasPrimaryClip() first, then check clipboard.primaryClipDescription.hasMimeType(MIMETYPE_TEXT_PLAIN) next.

It maybe crash if Kotlin check clipboard.primaryClipDescription.hasMimeType(MIMETYPE_TEXT_PLAIN) first, the check clipboard.hasPrimaryClip() next, right?

Code A

clipboard.addPrimaryClipChangedListener {
   if (clipboard.hasPrimaryClip() ) {
          if (clipboard.primaryClipDescription.hasMimeType(MIMETYPE_TEXT_PLAIN)) {

         }
   }
}

Code B

clipboard.addPrimaryClipChangedListener {
  if (clipboard.hasPrimaryClip() && clipboard.primaryClipDescription.hasMimeType(MIMETYPE_TEXT_PLAIN) ) {

  }
}

2 answers

  • answered 2018-11-08 08:04 Kunu

    if conditions run sequentially. That means it will first check the left condition and if the operator is AND and left condition return false then it won't check the right condition. So yes, you can merge two conditions.

  • answered 2018-11-08 08:18 s1m0nw1

    As mentioned in the comments, the principle behind this is described as "short circuiting":

    Short-circuit evaluation [...] is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression.

    That means clipboard.hasPrimaryClip() will always be evaluated. If it's false , the condition fails without looking any further. If it is true though, clipboard.primaryClipDescription.hasMimeType(MIMETYPE_TEXT_PLAIN) will be evaluated as well.