1

Take the hypothetical pseudo-code below as an example:

val a: Any? = ...
a?.takeIf { ... }
    ?.apply { ... }
    ?.let { ... }

I've read an article recently that suggested this kind of usage of the null safety operator creates redundant null checks when compiled into Java machine code. Here -- according to that article -- it would seem that when this is compiled, when a != null evaluates to true it will essentially check if a != null three times on the same variable. It might make since when you are dealing with a var property that has the potential to change values between checks. But in situations with immutable val properties, this creates redundant checks. If the above example is executed on each element over an enumerable data structure, this will scale the redundant checks linearly, making the end result 3 times more computationally complex than it needs to be.

Syntactically it makes a lot of sense to use Kotlin in this way. But if it produces wasteful/redundant checks like this, it seems like this is better to avoid this by explicitly null checking the variable with an if statement.

Is it appropriate to chain usages of null safety operator, especially when combined with lambdas that would check the same immutable variable multiple times? Or in other words, will doing so really result in excessive/redundant null checks in compiled java machine code?

4

0 回答 0