I work on an application in kotlin, but need to have a good java support.
The problem I found are kotlin's functions.
this is what I used to do
fun test(loader: (String) -> Int)
but this will compile into a Function1 from kotlin library and since I don't have kotlin library directly included in the jar because of jar size, it makes it harder for java developers because they have to download the kotlin library to be able to use this method.
I tried to use Supplier or Function interface from java but I found it a lot more difficult for kotlin developers since you have to provide a lot more variable types and null checks and together with generic arguments it's a pain..
Also tried to create my own interface like
@FunctionalInterface
interface Function: Function {
operator fun invoke(p: T): R
}
and function
fun test(loader: Function)
but it's the same as default java Function interface
so the only way that could work is to let the compiler compile my original function to my own functional interface instead of kotlin's one. But I don't have idea how to do that.
解决方案
In kotlin 1.4 they added ability to define our own functional interfaces like that
fun interface Function {
operator fun invoke(p: T): R
}
fun test(loader: Function) {
val result = loader("5")
}