Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
}
like image 251
aristotll Avatar asked Jun 04 '17 07:06

aristotll


People also ask

Can Java and Kotlin be used together?

Android Studio provides full support for Kotlin, enabling you to add Kotlin files to your existing project and convert Java language code to Kotlin. You can then use all of Android Studio's existing tools with your Kotlin code, including autocomplete, lint checking, refactoring, debugging, and more.

Can you call Kotlin code from Java?

One extremely useful feature in IntelliJ IDEA and Android Studio is the ability to see the compiled bytecode of your Kotlin code and then the decompiled Java code. For this, press Ctrl+Shift+A (Cmd+Shift+A on Mac) to invoke the action search, then type “Show Kotlin Bytecode” (or “skb”) and press Enter.

How does Kotlin inline function work?

An Inline function is a kind of function that is declared with the keyword "inline" just before the function declaration. Once a function is declared inline, the compiler does not allocate any memory for this function, instead the compiler copies the piece of code virtually at the calling place at runtime.


1 Answers

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.

like image 182
zsmb13 Avatar answered Sep 26 '22 12:09

zsmb13