Ralf Wickum
Ralf Wickum

Reputation: 3270

Kotlin integration in Java Code?

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;
}

}

Upvotes: 0

Views: 387

Answers (2)

yole
yole

Reputation: 97133

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.

Upvotes: 5

Mike Thomsen
Mike Thomsen

Reputation: 37506

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.

Upvotes: 0

Related Questions