Kotlin上限:`:Any`对Kotlin的泛型类型推断有何不同? [英] Kotlin Upper Bound: What difference does `:Any` make to Kotlin's generic type inference?

查看:228
本文介绍了Kotlin上限:`:Any`对Kotlin的泛型类型推断有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆