14 - Kotlin Generics
14 - Kotlin Generics
Kotlin generics
Read Discuss Courses Practice
Generics are the powerful features that allow us to define classes, methods
and properties which are accessible using different data types while keeping a
check on the compile-time type safety. Creating parameterized classes – A
generic type is a class or method that is parameterized over types. We always
use angle brackets <> to specify the type parameter in the program. Generic
class is defined as follows:
class MyClass<T>(text: T) {
var name = text
}
val my = MyClass("GeeksforGeeks")
Here, GeeksforGeeks has type String, so the compiler figures out that we are
talking about Myclass<String>
Advantages of generic:
Kotlin
Output:
Error:(10, 33) Kotlin: The integer literal does not conform to the
expected type String
In order to solve the above problem, we can create a generic type class that is
user defined accepts the different types of parameters in a single class. The
class Company of type is a general type class that accepts both Int and String
types of parameters.
Kotlin
Output:
GeeksforGeeks
1234
Variance:
Above, we have defined an OutClass class that can produce a value of type T.
Then, we can assign an instance of the OutClass to the reference that is a
supertype of it:
Note: If we have not used the out type in the above class, then given
statement will produce a compiler error.
Note: If we have not used the in type in the above class, then the given
statement will produce a compiler error.
Covariance:
Kotlin
Kotlin
Contracovariance –
It is used to substitute a supertype value in the subtypes, i.e. the generic
function/class may accept supertypes of the datatype it is already defined for,
e.g. a generic class defined for Number cannot accept Int, but a generic class
defined for Int can accept Number. It is implemented in Kotlin using the in
keyword as follows-
Kotlin
Type projections –
If we want to copy all the elements of an array of some type into the array of
Any type then it can be possible, but to allow the compiler to compile our code
we need to annotate the input parameter with the out keyword. This makes
the compiler to infer that input argument can be of any type that is a subtype
of the Any:
Kotlin
Output:
1
2
3
Star projections –
When we do not know about the specific type of the value and we just want to
print all the elements of an array then we use star(*) projection.
Kotlin
Output:
GeeksforGeeks
Similar Reads
Android - Create Group Kotlin | Language for
BarChart with Kotlin Android, now Official by
Google