例如,我有以下示例代码
fun f<T>( cb: (T, Int) -> Unit ): Unit {
println("f called with cb which accepts 2 arguments");
}
fun f<T>( cb: (T) -> Unit ): Unit {
println("f called with cb which accepts 1 argument");
f<T> {item, position -> cb(item) }
}
fun main(args : Array<String>) {
f { item -> }
f { item, position -> }
}
遗憾的是我希望f
函数选择正确的实现取决于我要传递给闭包的参数数量
目前 k ompiller给我错误:
(8, 7) : Overload resolution ambiguity:
internal fun <T> f(cb: (T, kotlin.Int) -> kotlin.Unit): kotlin.Unit defined in root package
internal fun <T> f(cb: (T) -> kotlin.Unit): kotlin.Unit defined in root package
在线沙箱中的代码:http://kotlin-demo.jetbrains.com/?publicLink=100745728838428857114-628607155
Compiller版本: org.jetbrains.kotlin:kotlin-gradle-plugin:0.10.770
UPD:youtrack的相关问题:https://youtrack.jetbrains.com/issue/KT-6939
答案 0 :(得分:3)
感谢@miensol,我意识到这是我的错误。我忘了在调用f()
时为T指定类型。
固定代码:
fun f<T>( cb: (T, Int) -> Unit ): Unit {
println("f called with cb which accepts 2 arguments");
}
fun f<T>( cb: (T) -> Unit ): Unit {
println("f called with cb which accepts 1 argument");
f<T> {item, position -> cb(item) }
}
fun main(args : Array<String>) {
f<String> { item -> }
f<Boolean> { item, position -> }
}