Kotlin界面上的lambda表达式 [英] lambda expression on interface in Kotlin

查看:165
本文介绍了Kotlin界面上的lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Java项目转换为Kotlin,我很惊讶接口使得Kotlin中的代码比使用Java更重。

I'm converting a project in Java to Kotlin and I'm surprise that interface made the code heavier in Kotlin than in Java.

示例
我想在MyFragment中设置MainActivity中的onBackPressListener。

Example: I want to set the onBackPressListener in MainActivity from MyFragment.

文件1:MainActivity,文件2:MyFragment,文件3:OnBackPressedListener(接口)

File 1: MainActivity, File 2: MyFragment, File 3: OnBackPressedListener (Interface)

Java中的文件1,Kotlin中的文件2,Java中的文件3:

File 1 in Java, File 2 in Kotlin, File 3 in Java:

activity.setOnBackPressed { /* Do something */ }

Kotlin中的文件1, Kotlin中的文件2,Java中的文件3:

File 1 in Kotlin, File 2 in Kotlin, File 3 in Java:

activity.setOnBackPressed(OnBackPressedListener { /* Do something */ })

Kotlin中的文件1,Kotlin中的文件2,Kotlin中的文件3:

File 1 in Kotlin, File 2 in Kotlin, File 3 in Kotlin:

activity.setOnBackPressed(object: OnBackPressedListener {
            override fun onBackPressed() {
                /* Do something */
            }
        })

是否可以在Kotlin中使用3个文件并使用lambda来设置监听器?
(在Kotlin中获取更多代码非常令人沮丧..)

Is it possible to have the 3 files in Kotlin and use lambda to set the listener ? (This is so frustrating to get more code in Kotlin..)

谢谢

推荐答案

lambda版本仅在kotlin与java互操作时有效,因为 SAM转换,请参阅官方文件

The lambda version works only when kotlin interop with java because SAM Conversions, see the official documents.


另请注意,此功能仅适用于Java互操作;由于Kotlin
具有适当的函数类型,因此不需要将函数自动转换为
的Kotlin接口实现,因此不支持

Also note that this feature works only for Java interop; since Kotlin has proper function types, automatic conversion of functions into implementations of Kotlin interfaces is unnecessary and therefore unsupported.

因此,如果你想使用lambda用纯kotlin设置监听器,你可以定义你的监听器 setOnBackPressed 这样的方法:

So if you want use lambda to set the listener with pure kotlin, you can define your listener and setOnBackPressed method like this:

var listener: (() -> Unit)? = null

fun setOnBackPressed(l: () -> Unit) {
    listener = l
}

然后通过以下方式调用它:

then invoke it by:

listener?.invoke()

这篇关于Kotlin界面上的lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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