There are some cases in Kotlin where the compiler will complain about a generic type parameter defined as <T>
and expects <T : Any>
. What is the difference?
When we define a collection with "*", it should contain the object of only that type. There should not be any mix and match between the data types inside a collection. If we use "Any", we can mix and match the data types, which means we can have multiple data types in a collection.
In Kotlin the Any type represents the super type of all non-nullable types. It differs to Java's Object in 2 main things: In Java, primitives types aren't type of the hierarchy and you need to box them implicitly, while in Kotlin Any is a super type of all types.
The out Keyword – In Kotlin, we can use the out keyword on the generic type which means we can assign this reference to any of its supertypes. The out value can only produced by the given class but can not consumed: class OutClass<out T>(val value: T) { fun get(): T { return value } }
Type Erasure. As with Java, Kotlin's generics are erased at runtime. That is, an instance of a generic class doesn't preserve its type parameters at runtime. For example, if we create a Set<String> and put a few strings into it, at runtime we're only able to see it as a Set.
The difference is that a plain <T>
means that it can be null
able. (which is represented by Any?
). Using <T: Any>
will restrict T
to non-nullable types.
So the difference is that <T>
is an implicit <T: Any?>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With