https://kotlinlang.org logo
Title
g

grahamborland

12/18/2018, 3:34 PM
Why does this compile?
private fun shouldNotCompile(optionalString: String?): Boolean {
        optionalString?.let {
            return true
        }
    }
I’ve completely forgotten to specify a return value for the case where the
let
is not entered.
🐛 1
e

Egor Trutenko

12/18/2018, 3:40 PM
Weeeell, it might be considered a bug, but... Compiler optimizes it to
boolean shouldNotCompile(@Nullable String optionalString) {
  return optionalString != null
}
Probably expected behavior due to optimizations.
a

Alan Evans

12/18/2018, 3:42 PM
Is what appears to be happening, but why would it do that though?
e

Egor Trutenko

12/18/2018, 3:44 PM
No, it's a bug.
fun shouldNotCompile(optionalString: String?): Boolean {
    optionalString?.let {
        println("something")
        return true
    }
}
Decompiles to
boolean shouldNotCompile(@Nullable String optionalString) {
      if (optionalString != null) {
         String var3 = "something";
         System.out.println(var3);
         return true;
      } else {
         return false;
      }
   }
Which sure should not happen.
i

ilya.gorbunov

12/18/2018, 4:19 PM
Yes, it's a bug related to contracts and control flow analysis https://youtrack.jetbrains.com/issue/KT-28061