Kotlin上限:`:Any`对Kotlin的泛型类型推断有何不同? [英] Kotlin Upper Bound: What difference does `:Any` make to Kotlin's generic type inference?
问题描述
在Kotlin for Android Developers
书之后,我们遇到了扩展功能
Following the Kotlin for Android Developers
book, we come across extension function
fun <T:Any> SelectQueryBuilder.parseList(parser: (Map<String,Any?>) -> T):List<T> = parseList(object:MapRowParser<T>{
override fun parseRow(columns: Map<String, Any?>): T = parser(columns)
})
我不确定为什么需要:Any
.
如果我将其写为fun <T> SelectQueryBuilder.parseList(...)
,则Android Studio会抱怨
If I write it as fun <T> SelectQueryBuilder.parseList(...)
, Android Studio complains that
当您重新添加:Any
时,该错误消失了.
whereas that error goes away when you add the :Any
back.
现在,就我而言,T
应该暗示T:Any
,尽管显然不是这样.这是为什么?它有什么区别?
Now, as far as I'm concerned, T
should imply T:Any
, though that is clearly not the case. Why is that? And what difference does it make?
推荐答案
现在,就我而言,
T
应该暗示T:Any
T
表示T:Any?
,其中Any?
与Java的Object
最接近.使用T:Any
您指定了不可为空的类型.
T
implies T:Any?
, where Any?
is the closest equivalent to Java's Object
. With T:Any
you specified a non-nullable type.
这篇关于Kotlin上限:`:Any`对Kotlin的泛型类型推断有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!