kotlin - 扩展功能问题
问题描述
在使用现有 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 将始终优先考虑类成员函数。由于Test:call(Object)
可能匹配,Kotlin 选择该方法而不是您的扩展函数。
带有添加参数的扩展函数以您期望的方式解析,因为Test
该类没有任何可作为先例的成员函数(没有匹配的签名),因此选择了您的扩展方法。
以下是关于如何解析扩展函数的 Kotlin 文档的链接:https ://kotlinlang.org/docs/reference/extensions.html#extensions-are-resolved-statically
推荐阅读
- jquery - jQuery:求和多个选择值
- angular - 以编程方式获取@ngrx/store-devtools 的状态
- node.js - 无法理解 Node Express 的各种 API
- node.js - 如何通过 pg-promise 使用 JSONB 操作
- python - 错误:unindent 不匹配任何外部缩进级别(制作 reddit 机器人)
- linux - RAM中的页表在哪里?
- c# - ASP.NET MVC 5 POST 复选框,用于使用 Ajax 的 onclick 控制器
- javascript - 如何在不同设备上连续显示固定数量的图像
- sql - 第一次简单的Oracle查询速度极慢,无法控制数据库?
- java - 如何从一个活动传递数据,然后在另一个活动的 recyclerview 中检索?