当泛型类型绑定到 Any 时,kotlin 重载解析歧义

Luk*_*der 5 generics overload-resolution kotlin

考虑这段代码

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)
}
Run Code Online (Sandbox Code Playgroud)

a.m(l)调用似乎不明确,并出现以下错误:

重载解析歧义: public final fun m(t: Any): main.A 中定义的单位 public final fun m(t: List<Any>): main.A 中定义的单位

我的直觉告诉我,m(t: List<T>)重载应该更具体,但我的直觉已经错误了一次,当时我在 Java 中遇到过类似的情况

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

a.m(l as Any)
Run Code Online (Sandbox Code Playgroud)

但是我怎样才能明确地调用所需的m(t: List<T>)重载呢?铸造a.m(l as List<Any>)不起作用。

Luk*_*der 1

辅助功能可以帮助:

fun <T> A<T>.mList(l: List<T>) {
    this.m(l);
}
a.mList(l)
Run Code Online (Sandbox Code Playgroud)

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