[英]Kotlin generates inner class for lambda
In my code, i have something like this: 在我的代码中,我有这样的事情:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenter.onCreate()
fabContainer.onClick {
presenter.onLoginButtonClicked(...)
}
}
When i decompile the apk and check byteCode, something like this appears: 当我反编译apk并检查byteCode时,出现如下内容:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.presenter.onCreate();
Sdk23ListenersKt.onClick((ProgressFloatingActionButton) _$_findCachedViewById(com.prozis.prozisgo.prozisgo.R.id.fabContainer), new ActAuthLogin$onCreate$1(this));
}
final class ActAuthLogin$onCreate$1 extends Lambda implements Function1<View, Unit> {
final /* synthetic */ ActAuthLogin this$0;
ActAuthLogin$onCreate$1(ActAuthLogin actAuthLogin) {
this.this$0 = actAuthLogin;
super(1);
}
public final void invoke(View it) {
this.this$0.getPresenter().onLoginButtonClicked(StringsKt__StringsKt.trim(((EditText) this.this$0._$_findCachedViewById(R.id.email)).getText()).toString(), StringsKt__StringsKt.trim(((EditText) this.this$0._$_findCachedViewById(R.id.password)).getText()).toString(), ((CheckBox) this.this$0._$_findCachedViewById(R.id.rememberEmail)).isChecked());
}
}
Why is this class created and how can i avoid it? 为什么要创建这个类,我该如何避免它? Is this normal Kotlin byte code, i tought lambdas were resolved to static methods inside the class they were called in.
这是正常的Kotlin字节代码,我认为lambdas被解析为它们被调用的类中的静态方法。
A lambda is compiled to a static method if it doesn't reference anything from the surrounding context. 如果lambda不引用周围上下文中的任何内容,则将其编译为静态方法。
In your example, you're referencing presenter
, which is an instance field of the activity class. 在您的示例中,您正在引用
presenter
,它是活动类的实例字段。 In order to capture that reference in the onClick
handler, it's necessary to create an instance of a new class (in this case, Kotlin captures the reference to the activity class and accesses the presenter through its property). 为了在
onClick
处理程序中捕获该引用,必须创建一个新类的实例(在这种情况下,Kotlin捕获对activity类的引用并通过其属性访问presenter)。
There is no way to avoid creating an extra class here, either with Kotlin or with plain Java. 无论是使用Kotlin还是使用普通Java,都无法避免在这里创建额外的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.