在科特林中用泛型覆盖函数
Overriding function with generics in kotlin
例如我有以下示例代码
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
函数选择正确的实现取决于我要传递给闭包的参数数量
目前 kompiller 给我错误:
(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
编译器版本:org.jetbrains.kotlin:kotlin-gradle-plugin:0.10.770
UPD:youtrack 上的相关问题:https://youtrack.jetbrains.com/issue/KT-6939
感谢@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 -> }
}
例如我有以下示例代码
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
函数选择正确的实现取决于我要传递给闭包的参数数量
目前 kompiller 给我错误:
(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
编译器版本:org.jetbrains.kotlin:kotlin-gradle-plugin:0.10.770
UPD:youtrack 上的相关问题:https://youtrack.jetbrains.com/issue/KT-6939
感谢@miensol,我意识到这是我的错误。我在调用 f()
.
固定代码:
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 -> }
}