

This is how generics is interpreted by Kotlin compiler. Take a look at the main method, where we have dynamically defined its value at the run by proving the value type, while creating the object of this class. In the above piece of code, we are creating one class with generic return type, which is represented as.

Println("I am getting called with the value "+input) In the following example, we will see how to use generic data types in Kotlin programming language. Generally, in Kotlin generics is defined by where “T” stands for template, which can be determined dynamically by Kotlin complier. It is better to go for generic data type whenever we are not sure about the data type we are going to use in the application. Let us learn something more about generics in Kotlin.

This is possible because “Int” is a subclass of Number class, hence the type conversion happens automatically at runtime and produces the output as “1”. In the above code, we have declared one “integer” and later we have assigned that variable to a number variable. The following example depicts how generics is implemented in Kotlin. As per the example, List is a class in Kotlin, whereas List is a type in Kotlin. In Kotlin, a class and a type are totally different concepts. Implementation wise, generics is pretty similar to Java but Kotlin developer has introduced two new keywords “out” and “in” to make Kotlin codes more readable and easy for the developer. In this chapter, we will learn how Kotlin implements Generics and how as a developer we can use those functionalities provided inside the generics library. Val turns: Turns = Gson().fromJson(pref.Like Java, Kotlin provides higher order of variable typing called as Generics. So that you can just call Gson and not worry about the TypeToken at all: val turns = Gson().fromJson(pref.turns) This solves the problem: val turnsType = object : TypeToken>().
