为什么 Lambda 表达式对于 Kotlin 和 Java 类的行为不同? [英] Why do Lambda expressions behave differently for Kotlin and Java classes?

查看:33
本文介绍了为什么 Lambda 表达式对于 Kotlin 和 Java 类的行为不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我可以将 Lambda 用于 java.lang.Thread 类,而不能用于 MyThread?

Why can I use Lambda for the class java.lang.Thread, but not for MyThread?

interface MyRunnable{
    fun run()
}

class MyThread(runnable : MyRunnable){    
}

fun test(){
    Thread({})     // All Alright

    MyThread({})   //Exception. Type mismatch <<-- Why ?
}

查看此示例的链接:https://try/#kotlinlang.org/UserProjects/tbs79qfkh50psp7r3qrdrinrmt/sfkpjq1bjvg4r6d5rmnu6mp4a8

推荐答案

来自 SAM 转换:

请注意,此功能仅适用于 Java 互操作;由于 Kotlin 具有适当的函数类型,因此无需将函数自动转换为 Kotlin 接口的实现,因此不受支持.

Note that this feature works only for Java interop; since Kotlin has proper function types, automatic conversion of functions into implementations of Kotlin interfaces is unnecessary and therefore unsupported.

换句话说,只有调用 Java 才支持使用 { ... } 语法.公开理由是您可以执行以下任一操作:

In other words, using { ... } syntax is only supported for calls to Java. The public rationale is that you could do either of:

  1. 让您的 MyThread 构造函数将一等函数类型作为参数.

  1. Have your MyThread constructor take a first-class function type as a parameter.

使用对象表达式:

MyThread(object : MyRunnable {
    override fun run() {}
})

这显然相当冗长.但是,根据 this Kotlin 票证,lambda 语法实际上只是 Java 的一部分互操作,不是核心语言的一部分,所以需要一些仔细的设计来做更多的事情.

This is obviously fairly verbose. However, according to this Kotlin ticket, the lambda syntax is actually only part of the Java interop, not part of the core language, so would take some careful design to do anything more.

这篇关于为什么 Lambda 表达式对于 Kotlin 和 Java 类的行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆