仍然无法为Val分配Kotlin通用功能吗?
在Kotlin中,我可以将功能分配给val
。
fun intListCat(a: List<Int>, b: List<Int>): List<Int> = a.plus(b)
fun testIntListCat() {
val f = ::intListCat
println( f( listOf(1,2), listOf(30,40) ) )
}
但是,当我制作函数通用时,我无法将其分配给val
。
fun<T> listCat(a: List<T>, b: List<T>): List<T> = a.plus(b)
fun testListCat() {
// error: Not enough information to infer type variable T.
val f1 = ::listCat
println( f1( listOf(1,2), listOf(30,40) ) )
// error: Unresolved reference T.
val f2: (List<T>, List<T>) -> List<T> = ::listCat
println( f2( listOf(1,2), listOf(30,40) ) )
}
令我惊讶的是,对简单函数的微小变化似乎使其在Kotlin中取消了高阶功能的资格,该功能的目的是尽可能发挥作用。
两年多以前,有一个类似Kotlin社区支持页面上的问题。社区无法确定回答。 Kotlin团队没有回应。
我只是想知道Kotlin或程序员知识从那以后是否有任何变化,以允许2022年将通用函数分配给val
?
我正在MacOS 11.3.1上使用Java 17.0.2运行Kotlin 1.6.20。
In Kotlin, I can assign a function to a val
.
fun intListCat(a: List<Int>, b: List<Int>): List<Int> = a.plus(b)
fun testIntListCat() {
val f = ::intListCat
println( f( listOf(1,2), listOf(30,40) ) )
}
But when I make the function generic, then I'm unable to assign it to a val
.
fun<T> listCat(a: List<T>, b: List<T>): List<T> = a.plus(b)
fun testListCat() {
// error: Not enough information to infer type variable T.
val f1 = ::listCat
println( f1( listOf(1,2), listOf(30,40) ) )
// error: Unresolved reference T.
val f2: (List<T>, List<T>) -> List<T> = ::listCat
println( f2( listOf(1,2), listOf(30,40) ) )
}
I'm surprised that a minor change to a simple function seems to disqualify it as a higher-order function in Kotlin, which aims to be as functional as possible.
More than two years ago, there was a similar question on a Kotlin community support page. The community couldn't answer it definitively. And the Kotlin team didn't respond.
I was just wondering if anything changed with Kotlin or programmer knowledge since then, to allow a generic function to be assigned to a val
in 2022?
I'm running Kotlin 1.6.20 with Java 17.0.2 on macOS 11.3.1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,这是不可能的。对于
val f1 = :: ListCat
要按照您想要的方式工作,f1
也需要是通用的,但是本地属性不能是通用的。通过明确指定类型并用实际类型替换
t
,您 can nistion:: ListCats
to local属性:尽管现在您无法通过
f
的其他类型的列表,这可能是不可取的。另一方面,非本地属性可以是通用的,但是它们的类型参数必须在接收器参数中使用,这意味着该属性必须是扩展属性,因此这可能对您所能有所帮助试图做。
No this is not possible. For
val f1 = ::listCat
to work the way you want,f1
would need to be generic too, but local properties cannot be generic.By specifying the type explicitly and substituting
T
with an actual type, you can assign::listCats
to a local property:Though now you cannot pass other types of lists to
f
, which is probably undesirable.On the other hand, non-local properties can be generic, but their type parameter must be used in the receiver parameter, which means that the property must be an extension property, so this probably isn't going to be helpful to whatever you are trying to do.