null or empty lambda as default value

Paweł Byszewski picture Paweł Byszewski · Aug 5, 2016 · Viewed 13.9k times · Source

which solution is better? use nullable lambda or pass empty lambda as default parameter? would kotlin optimize somehow empty lambda ? or create new instance that do nothing?

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

Unfortunately I do not understand generated byte code. Lets analyze

val test11 = Test1()

after decompilation gives us

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

and finally as a lambda is passed something like this

var1 = (Function0)null.INSTANCE;

edit: the hidden questions is: How does Kotlin treat empty lambda as default value?

Answer

yole picture yole · Aug 5, 2016

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

The decompiler used in IntelliJ IDEA does not always handle Kotlin bytecode particularly well, so what you see in its output in this case does not reflect what actually happens. In reality, the empty lambda will be compiled to a singleton nested class implementing the corresponding FunctionN interface with an empty body, and the singleton instance will be used as the default value.

See my talk slides for more information on how default parameters are implemented in Kotlin.