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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Informatic0re
  • 6,300
  • 5
  • 41
  • 56

2 Answers2

31

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);
Alexander Udalov
  • 31,429
  • 6
  • 80
  • 66
  • 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. – Informatic0re Jun 17 '15 at 06:00
  • 4
    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. – Alexander Udalov Jun 17 '15 at 06:59
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

ligi
  • 39,001
  • 44
  • 144
  • 244
  • 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. – Christopher Perry Dec 14 '22 at 22:50