How to avoid boxing of inline class for function interface

I am trying to use inline classes in performance critical code and thus would like to avoid boxing.
I understand the documentation states that when using a inline class in a generic type (kotlin.Function<out R> in my case) it will be boxed.
E.g.:

inline class MyInt(val i: Int)

fun foo(i: MyInt, f: (MyInt) -> Unit) {
    f(i) // i is boxed
}

One way to get around this is to create a new function interface, e.g.

interface MyFun {
    operator fun invoke(i: MyInt)
}

fun foo2(i: MyInt, f: MyFun) {
    f(i) // i is not boxed
}

But this has other problems: Cannot use lambdas, cannot pass kotlin.Functions directly.

Is there another, more elegant solution to this?

4 Likes