Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Kotlin extension in android java class

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

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

then in Java use it like:

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

is this possible?

like image 755
Informatic0re Avatar asked Jun 16 '15 21:06

Informatic0re


Video Answer


1 Answers

Kotlin's extension functions are compiled to JVM methods taking the receiver as the first parameter. If your extension function is declared on the top level, for example in a file named file.kt:

package foo

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

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

import foo.FileKt;

...

String someString = "blabla";
FileKt.getSomething(someString);
like image 171
Alexander Udalov Avatar answered Oct 06 '22 00:10

Alexander Udalov