Why do Lambda expressions behave differently for Kotlin and Java classes? [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:27:01

问题:

This question already has an answer here:

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 

Link to check this example: https://try.kotlinlang.org/#/UserProjects/tbs79qfkh50psp7r3qrdrinrmt/sfkpjq1bjvg4r6d5rmnu6mp4a8

回答1:

From the docs on SAM conversions:

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.

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

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

  2. Use an object expression:

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

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.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!