Use Kotlin extension in android java class

2019-04-25 08:33发布

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?

2条回答
做自己的国王
2楼-- · 2019-04-25 08:40

You can mix kotlin and java ( use/call kotlin classes in java classes ) But what you want here is use a kotlin feature in java - this is not possible

查看更多
狗以群分
3楼-- · 2019-04-25 08:48

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);
查看更多
登录 后发表回答