简体   繁体   English

Kotlin 中接口的 Lambda 实现

[英]Lambda implementation of interface in kotlin

What would be the equivalent of that code in kotlin, nothing seems to work of what I try:什么相当于 kotlin 中的代码,我尝试的似乎没有任何效果:

public interface AnInterface {
    void doSmth(MyClass inst, int num);
}

init:在里面:

AnInterface impl = (inst, num) -> {
    //...
}

If AnInterface is Java, you can work with SAM conversion :如果AnInterface是 Java,您可以使用SAM 转换

val impl = AnInterface { inst, num -> 
     //...
}

Otherwise, if the interface is Kotlin...否则,如果接口是 Kotlin...

interface AnInterface {
     fun doSmth(inst: MyClass, num: Int)
}

...you can use the object syntax for implementing it anonymously: ...您可以使用object语法匿名实现它:

val impl = object : AnInterface {
    override fun doSmth(inst:, num: Int) {
        //...
    }
}

如果您将接口及其实现都重写为 Kotlin,那么您应该删除接口并使用函数类型:

val impl: (MyClass, Int) -> Unit = { inst, num -> ... }

You can use an object expression您可以使用 对象表达式

So it would look something like this:所以它看起来像这样:

val impl = object : AnInterface {
    override fun(doSmth: Any, num: Int) {
        TODO()
    }
}

you can also do something like this, using @lambda label你也可以做这样的事情,使用@lambda标签


interface AnInterface {
     fun doSmth(inst: MyClass, num: Int)
}

val impl = AnInterface lambda@{inst, num ->
    //..
}

To anyone who is reading this in 2022, Kotlin now has Functional (SAM) Interfaces.对于 2022 年阅读本文的任何人,Kotlin 现在拥有功能 (SAM) 接口。 Please see https://kotlinlang.org/docs/fun-interfaces.html请参阅https://kotlinlang.org/docs/fun-interfaces.html

Maybe it will save others some time depending on your use case.根据您的用例,也许它会为其他人节省一些时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM