如何在 Kotlin 中以 lambda 形式实现函数式接口?

Chr*_*iss 6 lambda kotlin functional-interface

我想将函数式 kotlin 接口(具有单个抽象方法的接口)实现为 kotlin lambda。怎么做?

\n\n

Kotlin 接口

\n\n
@FunctionalInterface\ninterface Foo{\n  fun bar(input: String): String \n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

Kotlin 实现

\n\n
fun createFoo(): Foo {\n   return { input: String -> "Hello $input!" }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

\xe2\x86\x91 无法编译 \xe2\x86\x91

\n\n

它必须作为对象来实现,这非常丑陋。

\n\n
fun createFoo() = \n     object : Foo{\n            override fun bar(input: String)= "Hello $input"\n     }\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

编辑:将我的示例界面从 java 更正为 kotlin

\n

ant*_*i93 5

只需将fun关键字添加到您的接口声明中:

fun interface Foo {
    fun bar(input: String): String 
}
Run Code Online (Sandbox Code Playgroud)

它是 Kotlin 中函数接口的表示法(而不是@FunctionalInterfaceJava 中的注释)。

现在你可以像这样实现它:

Foo { input: String -> "Hello $input!" }
Run Code Online (Sandbox Code Playgroud)

查看更多: https: //kotlinlang.org/docs/fun-interfaces.html


Chr*_*iss 3

自 Kotlin v1.4 起

1.4 版将支持 SAM 转换,并采用新的类型推断算法。

看:


Kotlin v1.4 之前

如果伴生对象实现invoke采用 lambda 的函数,则它可以工作。

Kotlin 接口

interface Foo{
  fun bar(input: String): String

   companion object { 
      inline operator fun invoke(crossinline function: (String) -> String) =
                object : Foo{
                    override fun bar(input: String) = function(input)
                } 
   } 
}
Run Code Online (Sandbox Code Playgroud)

Kotlin 实现

fun createFoo()= Foo { input: String -> "Hello $input!" }
Run Code Online (Sandbox Code Playgroud)

在 kotlin 中定义的功能/SAM 接口在设计上无法实现为 Kotlin lambda,请参阅KT-7770

在 Kotlin 中,函数式 / SAM 接口被视为反模式,应改为声明函数类型:(String)->String。函数类型可以表示为类型别名,使其看起来像一个接口:typealias Foo=(String)->String

注意:类型别名在 Java 代码中不可见,仅在 Kotlin 中可见!