-3

There are Code A、Code B and Code C.

  1. Is Code A equivalent Code B ?

  2. Is Code A equivalent Code C ?

Code A

 if (IsRegistered(myContext) ) {

 }

Code B

if (IsRegistered(myContext) == true) {

}

Code C

if (IsRegistered(myContext) === true) {

}

Function

fun IsRegistered(myContext: Context): Boolean {
    val prefs = PreferenceManager.getDefaultSharedPreferences(myContext)

    var registeredStatus: Boolean? = prefs.getBoolean("IsRegistered", false)

    val isPro = myContext.resources.getBoolean(R.bool.IsProVersion)
    if (isPro) {
        registeredStatus = true
    }

    return registeredStatus!!    
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
HelloCW
  • 843
  • 22
  • 125
  • 310

3 Answers3

1

Code A and B are totally identical. The first one isn preferable since the equality check in B is just noisy. Code C, on the other hand, checks for referential equality:

Referential equality is checked by the === operation (and its negated counterpart !==). a === b evaluates to true if and only if a and b point to the same object. For values which are represented as primitive types at runtime (for example, Int), the === equality check is equivalent to the == check.

If you use your Code C though, the IDE (at least IDEA) does not like it and tells you that it's "deprecated" to use === on the Boolean type. It has been discussed here.

Code B should be recommended here.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
-1

Code A is equivalent Code B since

a === b evaluates to true if and only if a and b point to the same object.

UmAnusorn
  • 10,420
  • 10
  • 72
  • 100
-1
 if (IsRegistered(myContext) ) {

 }

Code in if will be executed if method IsRegistered returns true.

if (IsRegistered(myContext) == true) {

}

This will be executed if methods returns true. Actually it unnecessary comparison, but can be useful if IsRegistered may return null (because null isn't true), but in this case, its just additional 8 chars.

if (IsRegistered(myContext) === true) {

}

This is also equivalent to A and B, because Boolean is an primitive type, and === operator is the same as == (ref: https://kotlinlang.org/docs/reference/equality.html#referential-equality)

Cililing
  • 4,303
  • 1
  • 17
  • 35