?.let vs if not null

1 is thread-safe and works with longer. expressions.too()

2 isn’t and doesn’t. :wink:

As for the original question, I often use a third pattern when I deal with mutable properties because I like to keep my code “flat”:

class MyClass {
  var x:Int?
  var y:Int?
  var z:Int?

  fun doSomething_return() {
    val x = x ?: return
    val y = y ?: return
    val z = z ?: return

    // use x,y,z here as non-null ints
  }

  // to compare with the other patterns:

  fun doSomething_let() {
    x?.let { x ->
      y?.let { y ->
        z?.let { z ->
          // use x,y,z here as non-null ints
        }
      }
    }
  }

  fun doSomething_javalike_not_threadsafe() {
    if (x != null && y != null && z != null) {
      // use x!!, y!!, z!! here as non-null ints
    }
  }

To be honest, the java-way is really the shortest and best readable, too bad it is not threadsafe, so not recommended.

Both ways are equivalent, as in bytecode this:

variable?.let { //... }

is translated into this:

if (variable != null) { //... }

So, use the one that better suits you.
For me, using a “let” to perform an “if” is not the proper way. “let” is aimed to be used to transform the objects into something that you will need later.

1 Like