16

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 Answers 2

32

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);
Sign up to request clarification or add additional context in comments.

2 Comments

But I can not call someString.getSomething()? What I thought would be possible is to mix up the languages. "Changing" the String class with Kotlin and use these changes in java.
No, you can't. Extension functions/properties in a package are merely a syntactic sugar for static methods, they don't and can't change the corresponding receiver class. Also Java is not an extensible language in this regard, there's nothing in the Java Language Specification that would allow this.
7

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

1 Comment

You can't directly use it like you would in Kotlin, but you can call it in Java. Extension functions are just sugar around static calls where you would normally have to pass the receiver.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.