Hi! Is it possible to declare a function type in K...
# announcements
l
Hi! Is it possible to declare a function type in Kotlin and have it implement a marker Interface?
c
functions cannot implement interfaces, but they can be cast to SAMs if the SAM is written in Java
👍 1
d
*if the SAM is written in Java
👍 1
l
Hm, seems this works
Copy code
interface ITest : java.util.RandomAccess {
    fun callback()
}
val tmp = { println() } as ITest
ITest is declared in Kotlin
d
This will compile, but crash at runtime with
ClassCastException
.
l
Yes, it crashes... So the only options are declare this interface in Java or use object : ITest {...} ?
d
You can do something like this if you know the signature of the lambda:
Copy code
interface MyMarker

inline fun MyMarker(crossinline body: () -> Unit): MyMarker = object : MyMarker, () -> Unit {
    override fun invoke() = body()
}
However as you can see it returns
MyMarker
, so you then don't have a way to invoke it. Or you could make it return
() -> Unit
, but then you can't assign it to
MyMarker
.
I am questioning what you are trying to achieve in the first place, to be honest.
l
I'm trying to use JNA lib from Kotlin and define callbacks: a JNA callback is a SAM interface that extends a marker Callback (Java) interface. There is no problem declaring these interfaces in Kotlin, but I hoped it would be nice and easy to provide implementations of such callbacks using lambdas