Search code examples
kotlinkotlin-extension

Extension functions issue


Run into some difficulties while using extension functions with existing java api. Here some pseudocode

public class Test {

public Test call() {
    return this;
}

public Test call(Object param) {
    return this;
}

public void configure1() {
}

public void configure2(boolean value) {
}
}

Kotlin test

fun Test.call(toApply: Test.() -> Unit): Test {
return call()
    .apply(toApply)
}
fun Test.call(param: Any, toApply: Test.() -> Unit): Test {
return call(param)
    .apply(toApply)
}
fun main(args: Array<String>) {
val test = Test()
//refers to java method; Unresolved reference: configure1;Unresolved reference: configure2
test.call {
    configure1()
    configure2(true)
}
//refers to my extension function and works fine
test.call(test) {
    configure1()
    configure2(true)
}
}

Why only function with param works fine ? what’s the difference ?


Solution

  • Kotlin will always give precedence to the classes member functions. Since Test:call(Object) is a possible match, Kotlin selects that method rather than your extension function.

    The extension function with the added parameter is resolved the way you expect because the Test class does not have any member functions that would take precedent (no matching signature), so your extension method is selected.

    Here is a link to the Kotlin documentation as to how extension functions are resolved: https://kotlinlang.org/docs/reference/extensions.html#extensions-are-resolved-statically