kotlin 中接口的 Lambda 实现

问题描述 投票:0回答:5

Kotlin 中的代码相当于什么,我尝试的似乎没有任何效果:

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

初始化:

AnInterface impl = (inst, num) -> {
    //...
}
java methods lambda interface kotlin
5个回答
37
投票

如果

AnInterface
是Java,则可以使用SAM转换:

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

否则,如果接口是 Kotlin:

  • 从 Kotlin 1.4 开始,可以编写 函数式接口 :

    fun interface AnInterface {
         fun doSmth(inst: MyClass, num: Int)
    }
    val impl = AnInterface { inst, num -> ... }
    
  • 否则,如果界面无法正常工作

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

    您可以使用

    object
    语法来匿名实现它:

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

22
投票

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

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

4
投票

您可以使用对象表达式

所以它看起来像这样:

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

1
投票

对于 2022 年阅读本文的任何人来说,Kotlin 现在有了函数式 (SAM) 接口。请参阅https://kotlinlang.org/docs/fun-interfaces.html

也许它会节省其他人一些时间,具体取决于您的用例。


1
投票

您也可以使用

@lambda
标签

执行类似操作

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

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

© www.soinside.com 2019 - 2024. All rights reserved.