Kotlin Generics

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

A List can hold numbers, words or really anything. That's why we call the List generic.

Generics are basically used to define which types a class can hold and which type an object currently holds.

Syntax

  • class ClassName<TypeName>
  • class ClassName<*>
  • ClassName<in UpperBound>
  • ClassName<out LowerBound>
  • class Name<TypeName:UpperBound>

Parameters

ParameterDetails
TypeNameType Name of generic parameter
UpperBoundCovariant Type
LowerBoundContravariant Type
ClassNameName of the class

Remarks

Implied Upper Bound is Nullable

In Kotlin Generics, the upper bound of type parameter T would be Any?. Therefore for this class:

class Consumer<T>

The type parameter T is really T: Any?. To make a non-nullable upper bound, explicitly specific T: Any. For example:

class Consumer<T: Any>


Got any Kotlin Question?