简体   繁体   中英

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

}

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM