

This can be done by using generic constraints. You need to restrict a generic class to accept only certain parameterized. In earlier examples you saw that you can pass almost any parameterized type to a generic class, However, this may not always be desirable. You can define a generic interface in the same way you define a generic class. That’s how you can use this class with a String as well as with an Integer, both print statements would print True as the first item is an Integer while the second one is a String.Ī generic class is implemented just like a non-generic class the only difference lies in the additional parameter type that is passed to the generic class.Val items1 = Items(10) println(items1.value is Int) val items2 = Items("Hello") println(items1.value is String) Alternatively, you can create the instance without specifying the type, as the value passed is inferred automatically by the compiler.you can create an instance of this class by providing the type such as “Int” and passing in a value of that type for example “10”.let's say you have a class named “Items” that takes an argument of a generic parameter type “T” which is stored in “value ”.Type parameters: refer to the objects that will be passed and used with Generics. Generics: uses type parameters to reuse the same set of code with different types. This is where Generic Classes are useful.Duplicating your list code would be considered bad practice.


We’ll learn about generics classes and how they are used in kotlin.
