Call Kotlin inline function from Java
Asked Answered
N

2

17

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.
}
Nosography answered 4/6, 2017 at 7:20 Comment(1)
Why would expect in the first place that the Java compiler can magically inline functions? Java knows about java methods. How should it know about concepts in other languages?Sourpuss
S
24

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.

Simile answered 4/6, 2017 at 7:33 Comment(0)
V
0

Yes, u can do it

In Kotlin file:

    Builder.sendEvent { event ->
                    YandexMetrica.reportEvent(event)
                }
                .build();

In Java file:

    Builder.sendEvent(new Function1<String, Unit>() {
                    @Override
                    public Unit invoke(String event) {
                        Log.i("TEST", event);
                        return null;
                    }
                })
                .build();
Varix answered 3/9, 2020 at 13:37 Comment(1)
@PritamPawade Not really. The OP asked why the method does not get inlined in the compiled bytecode, not asking about how to call it.Phosphorus

© 2022 - 2024 — McMap. All rights reserved.