如何解决在Kotlin中使用Lambda表达式实现功能接口
@FunctionalInterface
interface Interf {
fun m1(num: Int)
}
fun main() {
val a: Interf = { 34 -> println("Hello world !!") }
}
编译时出现此错误
意外的标记(使用';'分隔同一行中的表达式)
Kotlin lambda函数语法与Java Lambda Expression是否有些不同?
解决方法
首先,这也不会在Java中编译:
@FunctionalInterface
interface Interf {
void m1(int num);
}
class Main {
public static void main(String[] args) {
Interf f = 34 -> System.out.println("Hello world !!"); //compilation error here
}
}
有几乎相同的错误:
error: ';' expected
Interf f = 34 -> System.out.println("Hello world !!");
^
为正确起见,应更改lambda参数的名称,以使其成为有效的Java identifier。
例如,它将编译:
Interf f = x -> System.out.println("Hello world !!");
现在,回到科特林。 1.4版引入了SAM conversions的语法:
fun interface Interf {
fun m1(num: Int)
}
可以用以下方法实例化
:val a = Interf { println("Hello world !!") }
此处保留了仅引用lambda参数的implicitly declared it
parameter公约。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。