Null or empty lambda as default value

which solution is better? use zero lambda or pass empty lambda as default parameter? could kotlin optimize somehow empty lambda? or create a new instance that does nothing?

class Test1(val action: () -> Unit = {})

Unfortunately, I do not understand the generated bytecode. Let's analyze

val test11 = Test1()

after decompilation gives us

private static final Test1 test11 = new Test1((Function0)null, 1, (DefaultConstructorMarker)null);

and finally how lambda is passed something like this

var1 = (Function0)null.INSTANCE;

edit: hidden questions: how does Kotlin treat an empty lambda as the default?

+7
lambda kotlin decompiling jvm-bytecode
source share
1 answer

It is definitely more idiomatic to pass an empty lambda rather than zero as the default value for the lambda parameter.

The decompiler used in IntelliJ IDEA does not always do well with the Kotlin butt code, so what you see on its output in this case does not reflect what is actually happening. In fact, an empty lambda will be compiled into a singleton nested class that implements the corresponding FunctionN interface with an empty body, and a singleton instance will be used as the default.

See my slides for more information on how the default options are implemented in Kotlin.

+10
source share

All Articles