Reputation: 2792
I have the following simple interface
interface A {
fun move(s:Boolean): Int
}
I have the following class
class X{
fun draw (x: A): String{
return "A"
}
fun main() {
val temp = A {
s -> 100
}
val a = draw ( { x -> 100} )
}
}
However both temp
and a
fail to be declared. temp
complains and the suggested fix is to convert to an anonymous object as follows (which defeats the whole purpose of using a SAM?)
val temp = object : A {
override fun move(s: Boolean): Int {
return 100
}
}
a
complains about a type mismatch. My question is why does this simple SAM fail? The method signature is the same.
Upvotes: 1
Views: 107
Reputation: 6495
Currently Kotlin only has SAM conversion for interfaces defined in Java.
For pure Kotlin code you're supposed to use a function type such as:
typealias A = (s: Boolean) -> Int
However, the syntax you expected will be supported in Kotlin 1.4 with interface defined as fun interface
.
As announced here:
What to Expect in Kotlin 1.4 and Beyond
and tracked as KT-7770
Upvotes: 1
Reputation: 19595
Kotlin 1.4 has support for SAM conversions for Kotlin interfaces, in addition to the Java interface SAM conversion available in previous versions. See:
With 1.4, you do need to define your interface as a "functional" interface:
fun interface A {
fun move(s:Boolean): Int
}
Upvotes: 0