空或空lambda作为默认值 [英] null or empty lambda as default value

查看:269
本文介绍了空或空lambda作为默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种解决方案更好?使用可为空的lambda或将空lambda作为默认参数传递? Kotlin会优化空lambda吗?还是创建什么都不做的新实例?



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



不幸的是,我不理解生成的字节码。让我们分析



val test11 = Test1()



反编译后给我们



私有静态最终Test1 test11 = new Test1((Function0)null,1 ,,(DefaultConstructorMarker)null);



最后,随着lambda的传递,像这样的东西



var1 =(Function0)null.INSTANCE;



编辑:
隐藏的问题是:Kotlin如何将空lambda视为

解决方案

传递空的lambda而不是null作为lambda参数的默认值肯定是更习惯的做法。



IntelliJ IDEA中使用的反编译器并不总是能够很好地处理Kotlin字节码,因此在这种情况下,您在输出中看到的内容并不能反映实际情况。实际上,空的lambda将被编译为单例嵌套类,该单例嵌套类实现具有空主体的相应 FunctionN 接口,并且单例实例将用作默认值。 / p>

请参见我的演讲幻灯片,详细介绍了如何在Kotlin中实现默认参数。


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?

解决方案

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.

这篇关于空或空lambda作为默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆