Maxim
Maxim

Reputation: 1254

Is it possible to inject pure Java code into Kotlin?

Actually I don't need this feature and asking just out of interest.

With C language it's possible to use assembler code within source code.

Is it possible with Kotlin?

For instance, define inline fun with @Java annotation. As the result all invocations of this function will be replaced with bytecode as it was compiled by javac.

Upvotes: 1

Views: 208

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170733

In principle you could write a method which takes Java code as a string, wraps it into a class and uses javax.tools.JavaCompiler to compile it and use it as e.g.

val x = inlineJava[Int]("""
int sum = 0;
int size = 10;
for (int i = 0; i < size; i++) { sum++; }
return sum;
""")

(actually implementing inlineJava left as an exercise). Though I must admit I can't think of a good reason to.

Upvotes: 1

cd1
cd1

Reputation: 16534

No.

A Kotlin file (.kt) can only contain Kotlin code. You can create a Java file (.java) and use it interchangeably with your Kotlin code, though.

Upvotes: 1

Related Questions