在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
Compiller版本: 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 -> } }