扩展功能问题
Extension functions issue
运行 在使用现有 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)
}
}
为什么只有带参数的函数才能正常工作?有什么区别?
Kotlin 将始终优先考虑 classes 成员函数。由于 Test:call(Object)
是一个可能的匹配项,Kotlin 选择该方法而不是您的扩展函数。
带有添加参数的扩展函数按照您期望的方式解析,因为 Test
class 没有任何可以作为先例的成员函数(没有匹配的签名),所以您的扩展方法已选中。
这里是关于如何解析扩展函数的 Kotlin 文档的 link:https://kotlinlang.org/docs/reference/extensions.html#extensions-are-resolved-statically
运行 在使用现有 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)
}
}
为什么只有带参数的函数才能正常工作?有什么区别?
Kotlin 将始终优先考虑 classes 成员函数。由于 Test:call(Object)
是一个可能的匹配项,Kotlin 选择该方法而不是您的扩展函数。
带有添加参数的扩展函数按照您期望的方式解析,因为 Test
class 没有任何可以作为先例的成员函数(没有匹配的签名),所以您的扩展方法已选中。
这里是关于如何解析扩展函数的 Kotlin 文档的 link:https://kotlinlang.org/docs/reference/extensions.html#extensions-are-resolved-statically