null or empty lambda as default value

后端 未结 2 1429
南笙
南笙 2021-02-05 11:36

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?

2条回答
  •  时光说笑
    2021-02-05 12:15

    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.

提交回复
热议问题