https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
a

addamsson

07/11/2019, 9:32 AM
I have a problem with SAMs in Kotlin. I'm working on a library which has functions which accept a lambda. My problem is that I can't simply write this:
Copy code
fun myFun(someLambda: (A) -> B) {
    // ...
}
because if a java user would like to call it they would need to pass a
Function1
to it which is not very good UX. If I create a SAM instead:
Copy code
fun myFun(someSam: Function<A, B>) {
    // ...
}
then it is cumbersome for Kotlin users. What I've been doing so far is that I went the SAM way and added an extension function for all of these functions for Kotlin users which just translates to the SAM function:
Copy code
inline fun <A, B> MyClass.someFun(crossinline fn: (A) -> B) {
    return someFun(object : Function<A, B> {
        override fun accept(value: A): B {
            return fn.invoke(value)
        }
    })
}
This method comes with a lot of boilerplate and it is also hard to maintain. Is there a better alternative to solve this problem?