在现有的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)
}
}
为什么只使用param函数才能正常工作?有什么不同?
发布于 2018-12-28 13:48:24
Kotlin将始终优先考虑类的成员函数。由于Test:call(Object)
可能匹配,因此Kotlin选择该方法而不是您的扩展函数。
添加了参数的扩展函数将按照您预期的方式进行解析,因为Test
类没有任何优先的成员函数(没有匹配的签名),因此选择了您的扩展方法。
下面是关于如何解析扩展函数的Kotlin文档的链接:https://kotlinlang.org/docs/reference/extensions.html#extensions-are-resolved-statically
https://stackoverflow.com/questions/53959481
复制相似问题