为什么Lambda表达式在Kotlin和Java类上表现不同? [英] Why do Lambda expressions behave differently for Kotlin and Java classes?

查看:216
本文介绍了为什么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() {}
})

这显然很冗长.但是,根据这张 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天全站免登陆