This question already has answers here:
Closed 2 years ago.
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 ?
}
Link to check this example: https://try.kotlinlang.org/#/UserProjects/tbs79qfkh50psp7r3qrdrinrmt/sfkpjq1bjvg4r6d5rmnu6mp4a8
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:
Have your MyThread
constructor take a first-class function type as a parameter.
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.