0

Example: In C-code it is possible to call parts of assembler code, like:

int main()
{
   //... stuff
   __asm
   {
      lea ebx, hal
      mov ecx, [ebx]hal.same_name ;
      mov esi, [ebx].weasel       ;
   }
   // .. further stuff
   return 0;
}

Is such a code integration possible for Kotlin code in Java (*.java) files?

(I am not talkin about JNI or C/C++ in Java!) I would like to extend already existing (AndroidStudio-) Java-Source-Code with Kotlin language.

//.. this is *.java file
public class MyAlreadyExistingJavaClass {

private int memberVar;

public MyAlreadyExistingJavaClass()
{

}

// this is Kotlin within *.java file
// extend this Java file with this constuctor in KOTLIN ?
// would make above default constructor unneccessary.
class MyAlreadyExistingJavaClass(number: Int = 0)
{
  memberVar = number;
}

}
0

2 Answers 2

5

Java does not provide any syntax for including snippets of code in Kotlin or any other language into a Java file. However, this is not necessary to accomplish your task. You can simply define the constructor you need as a factory function in a separate Kotlin file:

fun MyAlreadyExistingJavaClass() = MyAlreadyExistingJavaClass(0)

If you want to define a new method, rather than a constructor, you can use extension functions.

Sign up to request clarification or add additional context in comments.

Comments

0

I am a Groovy developer, not a Kotlin developer, but it looks like Kotlin provides a scripting API. Groovy, JavaScript and JRuby can all be called from within a Java class using the standard Java ScriptEngine API. You would want something like that to approximate inlining Kotlin within a Java class. I say approximate because it wouldn't be run directly like that assembly example, but would be passed through a ScriptEngine-compliant Kotlin implementation.

1 Comment

Whoever voted my comment down, why don't you provide a better response. You should know damn well that Java cannot in-line Kotlin code like that and expect it to compile and that this is closest approach to getting that the Java compiler supports.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.