简体   繁体   中英

Kotlin Upper Bound: What difference does `:Any` make to Kotlin's generic type inference?

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)
})

And I'm not sure why the :Any is necessary.

If I write it as fun <T> SelectQueryBuilder.parseList(...) , Android Studio complains that

错误信息

whereas that error goes away when you add the :Any back.

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?

Now, as far as I'm concerned, T should imply 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.

The :Any defines an upper bound for your generic type argument. As you can read in the Generics: Upper Bounds chapter of the Kotlin documentation, the default upper bound is Any? :

The default upper bound (if none specified) is Any?

Thus, <T> is equivalent to <T: Any?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM