null or empty lambda as default value

后端 未结 2 1430
南笙
南笙 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.

    0 讨论(0)
  • 2021-02-05 12:29

    Look the last paremter of the exposed function:

    internal fun showDialog(title: String, message:String?= null, okButtonAction: () -> Unit, koButtonAction:() -> Unit = {}){ //do things.....}
    
    0 讨论(0)
提交回复
热议问题