Use Kotlin extension in android java class

浪子不回头ぞ 提交于 2019-12-10 02:50:17

问题


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?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/30878506/use-kotlin-extension-in-android-java-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!