Search code examples
kotlininlinekotlin-interop

Call Kotlin inline function from Java


Exceptions.kt:

@Suppress("NOTHING_TO_INLINE")
inline fun generateStyleNotCorrectException(key: String, value: String) =
        AOPException(key + " = " + value)

In kotlin:

fun inKotlin(key: String, value: String) {
    throw generateStyleNotCorrectException(key, value) }

It works in kotlin and the function is inlined.

But when used in Java code, It just cannot be inlined, and still a normal static method call (seen from the decompiled contents).

Something like this:

public static final void inJava(String key, String value) throws AOPException {
    throw ExceptionsKt.generateStyleNotCorrectException(key, value);
// when decompiled, it has the same contents as before , not the inlined contents.
}

Solution

  • The inlining that's done by the Kotlin compiler is not supported for Java files, since the Java compiler is unaware of this transformation (see this answer about why reified generics do not work from Java at all).

    As for other use cases of inlining (most commonly when passing in a lambda as a parameter), as you've already discovered, the bytecode includes a public static method so that the inline function can be still called from Java. In this case, however, no inlining occurs.