5

im trying to understand the difference between the following two pieces of code in kotlin:

myVar?.let { print(it) } ?: run { print("its null folks") }

vs

myVar?.let { print(it) } ?:  print("its null folks")

are they equivalent ? is run just so we can use a block of code and the the other is for just a single statement ?

j2emanue
  • 60,549
  • 65
  • 286
  • 456
  • maybe it's an obvious consideration, but `run` returns the result of the code block you're supplying, so it must return the same type as the left side of the elvis operator – user2340612 Jul 09 '18 at 09:10
  • so other then providing a block to write code, the ?: run{} and ?: are the same right – j2emanue Jul 09 '18 at 09:15
  • to me yes, I don't see any difference. Moreover, you could do the same even without `run`, by simply creating and executing a lambda (e.g., `x ?: { doSomething(); doSomethingElse() }()`), which is more or less what `run` does – user2340612 Jul 09 '18 at 09:18

1 Answers1

15

Yes, they are equivalent. run allows you to use multiple statements on the right side of an elvis operator; in this case there's only one, so run is not needed.

yole
  • 92,896
  • 20
  • 260
  • 197