User1291
User1291

Reputation: 8182

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

error message

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?

Upvotes: 6

Views: 1998

Answers (2)

s1m0nw1
s1m0nw1

Reputation: 81859

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?>

Upvotes: 2

Marko Topolnik
Marko Topolnik

Reputation: 200138

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.

Upvotes: 13

Related Questions