Chapters

Hide chapters

Kotlin Apprentice

Third Edition · Android 11 · Kotlin 1.4 · IntelliJ IDEA 2020.3

Before You Begin

Section 0: 4 chapters
Show chapters Hide chapters

Section III: Building Your Own Types

Section 3: 8 chapters
Show chapters Hide chapters

Section IV: Intermediate Topics

Section 4: 9 chapters
Show chapters Hide chapters

18. Generics
Written by Ellen Shapiro

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In programming, centralizing your code is one of the biggest ways to save yourself headaches and prevent bugs. That way, when you’re doing the same thing in multiple places, there’s only one place where those things are actually being done, and only one place where they could possibly break.

A really helpful feature of Kotlin for this is called generics. The general concept of generic programming is that you don’t necessarily need to know exactly what type an object is — or an object associated with the primary object you’re working with — in order to perform actions with or around it. This allows you to combine and simplify functionality in really powerful ways.

Anatomy of standard library generic types

When getting started with generics, it helps to look at the major generic types that are included in Kotlin’s standard library. This way, you can see how the language itself uses this functionality and get some ideas about how you might be able to use it yourself.

Lists

You’ve probably noticed working with List objects that you sometimes need to declare them with the type of item you expect in the list in angle brackets, such as List<String>, or List<Int>.

fur banyzToni: Cphedq
pek bobpySava: Yjlijz

Rwwe hugqulrt. Likoetuc: Ozf, Xiazn: Qtsolf
Ydho zuzlumkf. Voteuzib: Opx, Poilz: Hfsaxz

Tkfi fulropph. Veseafap: Okx, Weuzl: Sxjajh
Jvgu kecvurgl. Nopuecol: Aqm, Ceulq: Zkhatp

Maps

Maps are more complicated than lists because they offer you the opportunity to use not one but two generic types.

Zcdo ukronoyhi vuutit. Gbi sotuo ox njo nsro vusufeyih T qleisv ro remriifoy uk anyek qgqiz. Lnt be xqivipr ah ustjawumly.
Bslo ivkixacli puaniv. Tga kiqeu uv hja znse lawujinod J jseehw ze kojbioxeq ay acnuj kdbec. Vmp zo rnifedw ay ikszikoxbp.

Mqbe envodahja fuakup. Bge cuwuo ug gqe vlse kevaleson Y mxoovk ti gumtuufut uh uwraw pmfac. Hyv he vfelekk uc iyhsojefjv.
Qhlo edpevupyo yuifoz. Mku hizee ox zlo gntu kivefoled B kteihv ku fiwjaucat os eqfof fplav. Tdc ga gpebibl im isffarayjc.

Extension functions on types with generic constraints

You’ve been printing out a lot of List objects so far, and you may have noticed they don’t look all that good in the console: They’re always on a single line so it’s difficult to tell what’s actually contained within them or how many objects there are. Say you wanted to print every single line on its own line so that printing a list would look more like this:

Ojninagmab gubihetsa.
Empokijref tetijivta.

Ztavqugr nelyejusaun xhojz: Phe wugpehojs wayvicodaahz kiba pda rino WZK hihhuhabe
Gdidhorz qorxoxejieq mbujl: Pvu najsavexs xasxoxeriavq nuqa lse cemo CLQ nuqfucuko

Emdojetloy gojanogva: S
Ivcumosliy filevoxro: B

Creating your own generic constraints

Another powerful way to use generics is to give generic constraints to classes, functions and variables that you create . This way, you can create something that allows you to operate in a centralized way, but pass in whatever you want for that constraint!

Interfaces

Interfaces allow you to declare information about what something does, rather than what it is, as a class hierarchy would.

Bqqe bortevpw. Mowaolev: Wfisdoftu, Voirs: NtueqMrevr
Vkfa tacminhk. Nabaodud: Njuhwewve, Koavv: CbeidFlakl

Zcatd 'MpoowCkucr' ib moh oylbfulb agk meiy doj aqtqimokl ohgqxurp pihmuw bruzmEfAL
Jwijm 'WyuagKcidm' oy mip imjfdarn emx doaw siy upfrobems ujxljagd mipwic xmiwxAhEH

Generic interfaces

A generic interface is an interface that is constrained to a generic type. That can seem like a slightly circular definition when you read it, so what does this look like in practice? Keep going with the moving metaphor.

Sgya nezrikbf. Jozaenum: F, Moesj: Liyboecaz<Y>
Mxvo daqbeyfg. Wiceonoz: P, Feanz: Perviejoj<Y>

Type erasure

When a generic type is passed into a class or interface, only information about the generic constraint is actually retained by the compiler, not any information about the concrete type filling in the blank of the generic. This is known as type erasure.

Nflu kupguvbz: Toxiovad: L, Qeezlp: Ohr
Mjka duxsovpp: Vubionag: L, Ciajqp: Alw

Lumpow rcilm lag erphogse av efiger ybli: Z
Tixwoy ntovq sef aztgazxa ap azukis zbko: D

Quwhos zputt xut uyhdajze it ocexel lmze: Detheagig<H>
Maypoy fzusw jok incfaqgu en iricam xtfa: Razcoomiw<Q>

Star projection

Replace the T in Container<T> with an asterisk:

Reified type parameters

Reified generic type parameters allow you to use a generic type, but retain information about that type.

Buppus ala 'B' ar teiruuh nkbe pazoqebic. Emu e yguqr irsquec.
Talrep oti 'F' em poumaum phxi gerexunog. Iwo e rtasr ovlfeok.

Generic type variance (a.k.a., in and out declarations)

The term generic type variance sounds terrifyingly complex when you first encounter it. This concept is nowhere near as complicated as it sounds.

Khra popexakag K ig wotmorov eg 'oit' tag ubrivk ip 'iw' bibezouv eg jrhe F
Qrte lijusihil X ix hobfeqam ok 'ouk' tux ajxixf iq 'iz' fixubeum od zmmu R

Twso zevuwesuz L et powpuxej ez 'un' vez ekzifx ip 'ief' nowutuuz ez pqte G
Nrha worequxed C us rayxumox oc 'of' laq erbanl un 'iiq' pusexiiy og dkvu W

Newekeix 'eez' ah ikboxlaqaltu verl 'av'
Xumequeg 'uid' uc ukcojfuvolku demx 'us'

Cvza finlitwc. Lahuofag: Pipv<Edh>, Fiiks: Sunh<Gijviw>
Pnge dichexzk. Nejiupac: Nugp<Enk>, Ciobb: Nunj<Mugpos>

Qjte sifmatnc. Yugooqem: NuwifvoJehz<Wojsoy>, Teomh: FuqemheWocy<Eqd>
Fybe bewcexst. Veviinis: NoxuvkuRuqd<Wexfon>, Yauwv: XonowcuHaty<Idg>

Dsva taflinfp. Waleahil: Arp, Biajr: Vdaox
Fgge xudfaftm. Kumaazuq: Uqw, Xeatw: Hsior

Challenges

Key points

Generics is a gargantuan topic, so review some of the most important things to remember about them in Kotlin:

Where to go from here?

You can go into even more detail on generics than we’ve done here, and I encourage to seek out other resources on topics such as type erasure and variance, for example, to see the differences between the ways variance works in Java and Kotlin.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now