【问题标题】:kotlin overload resolution ambiguity when generic type is bound to Any泛型类型绑定到 Any 时的 kotlin 重载解析歧义
【发布时间】:2020-11-09 21:20:28
【问题描述】:

考虑this code

fun main() {
    class A<T> {
        fun m(t: T): Unit {
            print("T")
        }
        fun m(t: List<T>): Unit {
            print("List<T>")
        }
    }
    
    val a: A<Any> = A()
    val l: List<Any> = listOf()
    a.m(l)
}

a.m(l) 调用似乎含糊不清,出现以下错误:

重载解析歧义:public final fun m(t: Any): Unit defined in main.A public final fun m(t: List): Unit defined in main.A

我的直觉告诉我,m(t: List&lt;T&gt;) 重载应该更具体,但我的直觉在过去已经错了一次,when I had a similar case in Java

我可以这样称呼“错误”的重载:

a.m(l as Any)

但我怎样才能显式调用所需的m(t: List&lt;T&gt;) 重载?投射 a.m(l as List&lt;Any&gt;) 不起作用。

【问题讨论】:

  • 避免使用Any ang go for (a new) 接口,它可以是任何东西 - 只是不要使用类 Any
  • @Neo:这个问题专门针对Any

标签: kotlin generics overload-resolution


【解决方案1】:

辅助功能可以提供帮助:

fun <T> A<T>.mList(l: List<T>) {
    this.m(l);
}
a.mList(l)

仍然对不涉及像这样的任何间接的替代方案感到好奇

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多