Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - <T> versus <T : Any>

Tags:

kotlin

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?

like image 567
Matthew Layton Avatar asked Jan 02 '20 12:01

Matthew Layton


People also ask

What is the difference between * and any in Kotlin generics?

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.

What is any type in Kotlin?

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.

What is the meaning of T in Kotlin?

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

What is type erasure Kotlin?

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.


1 Answers

The difference is that a plain <T> means that it can be nullable. (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?>.

like image 200
Adam Arold Avatar answered Oct 19 '22 16:10

Adam Arold