Chr*_*iss 6 lambda kotlin functional-interface
我想将函数式 kotlin 接口(具有单个抽象方法的接口)实现为 kotlin lambda。怎么做?
\n\nKotlin 接口
\n\n@FunctionalInterface\ninterface Foo{\n fun bar(input: String): String \n}\nRun Code Online (Sandbox Code Playgroud)\n\nKotlin 实现。
\n\nfun createFoo(): Foo {\n return { input: String -> "Hello $input!" }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n\xe2\x86\x91 无法编译 \xe2\x86\x91
\n\n它必须作为对象来实现,这非常丑陋。
\n\nfun createFoo() = \n object : Foo{\n override fun bar(input: String)= "Hello $input"\n }\nRun Code Online (Sandbox Code Playgroud)\n\n编辑:将我的示例界面从 java 更正为 kotlin
\n只需将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
1.4 版将支持 SAM 转换,并采用新的类型推断算法。
看:
如果伴生对象实现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 中可见!
| 归档时间: |
|
| 查看次数: |
4289 次 |
| 最近记录: |