首页 > 解决方案 > 扩展功能问题

问题描述

在使用现有 java api 的扩展函数时遇到一些困难。这里有一些伪代码

public class Test {

public Test call() {
    return this;
}

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

public void configure1() {
}

public void configure2(boolean value) {
}
}

Kotlin 测试

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

为什么只有带有参数的功能才能正常工作?有什么不同 ?

标签: kotlinkotlin-extension

解决方案


Kotlin 将始终优先考虑类成员函数。由于Test:call(Object)可能匹配,Kotlin 选择该方法而不是您的扩展函数。

带有添加参数的扩展函数以您期望的方式解析,因为Test该类没有任何可作为先例的成员函数(没有匹配的签名),因此选择了您的扩展方法。

以下是关于如何解析扩展函数的 Kotlin 文档的链接:https ://kotlinlang.org/docs/reference/extensions.html#extensions-are-resolved-statically


推荐阅读