Difference between classes of type Any and T in Kotlin?

2

In Kotlin I have run into several fragments of code where they use Any and / or generic classes (T), where the objective is to indicate that this variable can be of any kind.

According to official documentation Any is the superclass in kotlin, all classes inherit from it.

My doubts are:
What is the difference between both types of classes?
When and where to use each one?

    
asked by dámazo 06.11.2017 в 15:08
source

1 answer

2

I have no experience with Kotlin, but after reading the documentation Any is the root superclass of all (equivalent to object in C # for example). Every object inherits from Any , so every object is of type Any .

Generic types are something else. T is replaced in each case by the type of the object that is passed to the method, but there is no boxing or unboxing . You can think of it as a wildcard that is replaced by the corresponding type, and any in the step from one variable to another of type T , it is checked that both types match.

As for when to use each one, it is normal to always use generic drugs wherever possible. That way you will save on the one hand having to make at some point a cast at the correct type, and on the other the compiler will warn you at compile time of any error casting that you have in your code.

As I say I have no experience with Kotlin, but his philosophy is what I see practically traced to the .Net. And based on that, I would say that using Any is not appropriate in practically any context, since you lose all the advantages of object typing. Always use generics.

    
answered by 06.11.2017 в 15:50