Use Kotlin extension in android java class

Is it possible to use the kotlin extension in android java class? Example:

fun String.getSomething(): String { return "something" } 

then in Java use it like:

 String someString = "blabla"; someString.getSomething(); 

Is it possible?

+6
source share
2 answers

You can mix kotlin and java (use / call kotlin classes in java classes) But you want to use the kotlin function in java here - it's impossible

+2
source

Kotlin extension functions are compiled for JVM methods that take the receiver as the first parameter. If your extension function is declared at the top level, for example, in a file called file.kt :

 package foo fun String.getSomething(): String { return "something" } 

Then in Java you can call the static method from the corresponding class:

 import foo.FileKt; ... String someString = "blabla"; FileKt.getSomething(someString); 
+13
source

Source: https://habr.com/ru/post/989249/


All Articles