gpt4 book ai didi

generics - 是否可以在 Kotlin 中创建对伴随对象泛型方法的引用?

转载 作者:行者123 更新时间:2023-12-01 12:15:45 26 4
gpt4 key购买 nike

是否可以将变量的值设置为方法,其中该方法位于 Companion 对象上并具有类型参数?类似于以下内容:

class A {
companion object B {
fun <T>foo(n: T) { }
}
}

val b = A.B::foo<T>

最佳答案

不,类型系统中没有泛型函数引用的表示。例如,它没有量化类型,它可以表示您试图以类似 forall T . (T) -> Unit 的形式引用的函数。 .

您只能对泛型函数进行非泛型引用,为此您必须提供预期类型中的具体类型(它取自分配或传递引用的位置),例如,这将起作用:

class A {
object B {
fun <T> foo(n: T) { }
}
}

val b: (Int) -> Unit = A.B::foo // substitutes T := Int
val c: (String) -> Unit = A.B::foo // T := String here

fun f(g: (Double) -> Unit) = println(g(1.0))
f(A.B::foo) // also allowed, T := Double inferred from the expected type

关于generics - 是否可以在 Kotlin 中创建对伴随对象泛型方法的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48332295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com