https://kotlinlang.org logo
#announcements
Title
# announcements
a

Alexpl292

07/11/2019, 11:10 AM
Hi! Is it possible to define an extension function in java code? https://stackoverflow.com/questions/56987823/define-kotlin-extension-function-in-java-code
🚫 1
t

tseisel

07/11/2019, 12:30 PM
Define that function as
protected
in the body of the Java class :
Copy code
public abstract class BaseJava {
    protected void foo(String str, int bar) {
        // Implementation of your function.
        // Notice the signature : its first parameter is a String, which is the expected receiver of your extension function in Kotlin.
    }
}
In Kotlin, you could define this extension in each derived class :
Copy code
class Derived : BaseJava() {
    private fun String.foo(bar: Int): Unit = foo(this, bar)

    fun myFun() {
        "Hello World!".foo(42)
    }
}
But that sounds like a lot of efforts just to have a nicer syntax for some function calls. I'd stick with calling the
protected
method by passing the
String
parameter.
2 Views