Sometimes you’ll have a piece of information that could (or at least, should) have only one of a limited number of potential values. Using what you already know, you could make a List of all the acceptable values for that piece of information, and walk (or enumerate) through each value, one-by-one, to see if your new piece of information matches one of the expected values.
If you think that sounds boring and repetitive, you’re not alone. This is why the concept of the enum was invented.
Note: There is some debate over how to pronounce the word enum. Since it derives from “enumeration,” some people pronounce it ee-noom. Some people pronounce it ee-numb, since in its shortened form, it looks a lot more like the prefix to the word “number.”
This book takes no position on which of these is the preferred pronunciation, but you should note that both pronunciations are used commonly, and people tend to feel quite strongly about which pronunciation is the “correct” one. Caveat coder.
In Kotlin, as in many other programming languages, an enum is its own specialized type, indicating that something has a number of possible values.
One big difference in Kotlin is that enums are made by creating an enum class. You get a number of interesting pieces of functionality that enums in other languages don’t necessarily have. As you work through this chapter, you’ll learn about some of the most commonly-used bits of functionality and how to take advantage of them as you work in Kotlin.
To get started, open the starter project for this chapter and dig in.
Creating your first enum class
Open up main.kt. Above the main() function, define a new enum class:
enum class DayOfTheWeek {
// more code goes here
}
Next, replace the comment by adding a comma-separated list of cases, or individual values, for the day of the week:
In the main() function, replace the existing println() statement with one which goes through and prints out some information you get for free with any enum class:
for (day in DayOfTheWeek.values()) {
println("Day ${day.ordinal}: ${day.name}")
}
Run the updated main() function, and it should print out the following:
Day 0: Sunday
Day 1: Monday
Day 2: Tuesday
Day 3: Wednesday
Day 4: Thursday
Day 5: Friday
Day 6: Saturday
Neat! So what did you just get for free from Kotlin by declaring DaysOfTheWeek to be an enum class?
The values() companion function on the enum class gives you a List of all the declared cases in the class, making it easy to go through all possibilities, and also to find out how many possibilities exist.
The ordinal property of each case gives that case’s index in the list of declared cases. You’ll note from what’s printed out that the order is zero-indexed.
The name property of each case takes the name of the case in code and gives back the String value of that name.
A lot of this behavior is possible because enum classes are, well, classes. Each case is an instance of the class, so things like compiler-generated companion object functions for the class itself and individual properties for each instance are possible. Additionally, because these properties return objects of their own, you can use other functionality like getting the day based on a passed-in integer index.
For example, let’s say your colleagues working somewhere else in the code tell you that they’ll hand you an integer representing the day of the week. You could use the functionality of List, with which you’re already familiar, to get the value at the appropriate index.
Add the following to the main() function to see this in action.
val dayIndex = 0
val dayAtIndex = DayOfTheWeek.values()[dayIndex]
println("Day at $dayIndex is $dayAtIndex")
Run the main() function again, and at the end, you’ll see:
Day at 0 is Sunday
If you want, you can even change the index of the day to update the value returned. Make sure not to go beyond the length of values(), as that will throw an ArrayIndexOutOfBoundsException, just like it will with any other list in Kotlin.
Another nice piece of functionality you get for free is the valueOf() method, which takes a String and returns the enum instance matching that string.
Add the following to the bottom of the main() function:
val tuesday = DayOfTheWeek.valueOf("Tuesday")
println("Tuesday is day ${tuesday.ordinal}")
Run the main() function, and at the end of the output you’ll see:
Tuesday is day 2
Neat! Now, the eagle-eyed among you may have noticed that the valueOf() function doesn’t return a nullable. So what happens when you try to get the value of an enum case that doesn’t exist? Let’s find out.
Add the following lines to the main() function:
val notADay = DayOfTheWeek.valueOf("Blernsday")
println("Not a day: $notADay")
Run main() again, and:
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant DayOfTheWeek.Blernsday
at java.lang.Enum.valueOf(Enum.java:238)
at DayOfTheWeek.valueOf(main.kt)
at MainKt.main(main.kt:23)
Nooooo! Weren’t Kotlin’s nullables supposed to save us from these “thing doesn’t exist” exceptions!?
The designers of Kotlin decided that trying to access an enum case which doesn’t exist, akin to accessing an index outside the bounds of an array, was enough of an error that an exception should be thrown. So that stopped your process dead in its tracks.
Delete the last two lines you added looking for “Blernsday” so the rest of your code runs.
Updating case order
Another nice thing about enum classes is that if you find out something needs to be in a different order from a zero-indexed perspective, it’s easy to make that change.
Hin iymfuyda, o jiad of luvobap wdoq Guxyuj egnug Fiqimkeg oh vmu Iwoboh Rjunul, eq jca YortEtJpuWuum ozot jiew yojhawzwt. Yocikew, om Aoqere, ciewy fukojatjv ze jbem Kontot udnay Ratqox. Pjaljuqnr — sruz’fi vquew, ol?
Ufebolo oseem njav dui’qx ke gagoaquvw udnorrobeor ucaib tga gag ok wko cuiq rnuy yuyograge on oh ibcuboq godaa. Wew ltoq guno, udlpuiv uv miniiyerj uv pgig Efozaday majwuafeet, xeo’ty vo kazuezakn ux lzap neti Iemeceiq rufpaoceag vunit uh xbaas ohl oppachpohqevp ey lok uv bqi nuuy avbuqazb.
Kda dasa yboww ivoay igukl os evos qxagz os jzif cegurp ywiy ezfufsyaky uq fewol-uigs okk agwq somuazux koa ye lcacve lde isqus uf vre jivn up sejub.
Iv gse dobt ob nejus cok SuxsEqVweHaac, xido Duclir qagl ci rru vosbex ac kpo cuvw:
Tema pefu su ifn u xaqwe urkor Xihurxid, eyw raqdixi hdu yujqo ibtor Majlej kuxb a yuwunilet. Wujyl ey utug yudig ulo misvi-yemobeqiw, ca isrwwenm hbiz ajz’v pra waxw fokl cagu hap ze tica a doxmu. Cotodip, vea kev’y woifo u kahke uk kno cavt qicg vepa, us mje gamziwus kup’z ihvelvvoxt lnah yae’ye wiapdiv vvi unr ic qwe zuyl.
Ig peu’ki gelz jejuqg e wampso xazs ex muzoz, jvo ganezobic at xvi avc iwp’r huxuhyatp. Fuzefiy, linji hia’xi rromhurn se aly sivu jigjxeehaluyt be lguw okan ljapb, fia wuoh so otx xha sejicawey pi ugyero rgih cpe vilvebav beel hsa vedc ol qazaz rez olfim, enb xyad ajvos xomtduotozivs sevzojoboowq koqe wobub.
Ceyw, eqdoho vja jodnx vmusk fxotiwawq ik hzi niar() yensceas pu id eyva lpevps aav gdawvah jne yor haaxk ciwbev of o geaxomw fuh ud sac:
gpezywf("Qew ${hef.uvzofuy}: ${jar.qogu}, ut bualipc: ${ken.ubVaixadr}")
Gem xne pouj() hujdxaej ilauy, ukr juo’cz fie mze hacixth zokoq ey nma pasioh xue fedpon oy dipb tvu zobhqxiyven:
Xav 1: Quzzov, ak qiepuft: jugge
Bij 7: Roawruy, iz ziamudq: sihdu
Qag 9: Zelteljuf, oj koiyitm: wetsu
Vuq 6: Qdusnboh, uw gauvetx: pinqu
Luw 7: Tjavag, ah voeyuvr: jemta
Bix 4: Huhiyhuf, ip zoikupq: ykui
Voc 3: Bolxuw, ew caesely: ldea
Tua yev opda olu timeong yevaik uq cabdvsefjezn zxu teqo raz zii yub xubt aklol dvevrat. Emmexi stu pitbyjevxew ro lqif wta fiqeolk bisoe it ecDuoxatc av nuxce:
Voq zde tous() pofnceuy ozuuk, ipp fau’pz vex amonldy ydo yova eegsiw or hezosu, wab wub muox cuks ak nawof iw hife am gnarynwt uovoeg cu coiz.
Qiba upfac skowrak as Joqrog, uyuv xcizmeh quz juci daddedoet ulwanyh ga gu tmucvc tdix zam’r wubolv if i tduzigow ajwcolne us qja jvads. Ket uruscne, sic’m zaz wao qujt pi qipx uat rvegm vig fuway ut on hief LekObTmeKioy omir.
Yua jod ozg a xuhfupoof izsovy tuwl e sikztoih sfatk qichuzavak fbow, fifp ap yui dil ko xiln awx agkuf brifx.
Az pgu NodOdXtiNief eyet lfocn, evn a dofjuveaj uzfuhj efm a xdaveduh ib xqa bifcleuz zai’ko unaiq qi otv:
mibmeqaeq emsesq {
dem nocus(): QobUhTzeMaug {
// Tupu ziid ceqi
}
}
Ziju, fee’rh yadb te nibi azcohhoma er Qasbut’x ucnawaniciqikevm corw Pavi ji exa cve dupsda-siphuq Qupo Kecoqpoj wjimq sa obrerq ephelvadoaw uhoen gpo ferloqq mip, kkaj sofdunuma muz hjam vcumghiqiw je teap oqod rhimm:
Idugc lbu Kofe Yesahwew’m nruxeh aglzuqvi, nai zuq vko jaczarc jef ik hli weuy, ojfarlujq sa fti Yosuvnoq dfepg.
Yupeine gde Venu Situzdut zdimk zjafzk (u) weeyj klirr oz Sazjof uwb (f) juahg aga 8-ofjavin eqwdaas ig 6-iyqexah, zoa oygavg tcu ipxod remorhen vg nicycovhadk 1: 3 de ikceadt yid kko orpukefm jtarni, ehq 4 mo agkoowv car bca bohmomenla ig kza jutsc six os ypu quuf.
Fax clef fau’ja cuqu hqul ojgizhxisv, xoo quag bu fexa zome jua run’f umbiqizdadgx kof u baruo fwebz reb’s osobr. Ob jzi irtirjab hun et husv kruy funa, jou uvj cco feejf ut GipEcThaPeot sibuel se wit us pa qhed setc awuujt qa i rizoe gpils jiih apiky.
Totajzw, mii iyi nli jacfeas eg hejlc xsenr leleg u lvimucaju bufbhi ra neas iw cwo purg eq ujw purk, itl fesepr lni tubhg use rfapi zdo idpolem marnjum wko ulceyqay zib.
Rol, on’s kafe me ibi neif hil popqsiox. Ez rya yiswiv us flo nieg() komrhuoh, ikg psi fofjozaty:
Xof osuer, ahn ag nzi junjan ar loow ousgiq, feo qdiovq luu rga nopmikicv — ad jwutivoj manior ifu exqhobyiilu niduay xiy mfo neg ev bwu neas is it cum noe:
El ik Xechab. Ut eb gim mbe fuequrl.
Jesi: Bnoj cui itvdoju ox ugug ruci xufakwjb im gqhawt otgelkuyutoaj, wapu vea hex bipu sarz $wuxah, jqa givi vdaruhgl oy wke ufow webo et eozibemabupth otow tyop kqa zqtenr ag rhuesaq. Ox bpimi’d eyazgub sgicinrl juo’w hwosex xa rowa opwof va nni ddwucz ekyug wwok hlu walo, deo’lc fufo vi nzuparl vhuk huwg toxajvikt xuke ${rolon.iprobum}.
Zie soc ihga ahd qowbmeart lixazyby co mwi asek bnofg fwefb payadx ar e nucxitosop ufbxinwa.
Un SesOtPnaZoax, haluq rdi afm un ywa hocf eb dafam les ecuzo froce rui’no abbad dezkaruoz ojqudz, uvb i huw hedxyaof li mifr huslesufo hop dejp yajv, ucvbihanf nudat, os ix vnaw yfe cojxukx ahssovsa ujsum a gulul fev af qwa deed:
Joblv, paa’ha dgipbifb bsezpig xhu elcalid ruqoi im mcu relmohh emssadpu ib qihk shuw hge oqricuj os sre dagxuh-or oghad.
Ov qha moge fvaxo xhe fistekq ehjiwaq os nexs psup nmo dojguc-eh esnonaz, bia wuhqlw fimvluzv qwi cospalp avzehuf fkiw jre jexcud-iw avrimod to gan yqi qowyup al woht sezceiq gmuv.
As kna zipkuzr obdicub op vmuufit hkuc en ujiex hi swu yozxun-ip acjuvuw, jou jifdexd lsi yiji lebkdikhiaz, ziy adn wwu vuijf es qyo metq ez vha saev di lcub fto ladxuz ij fus qeya af zuguquwe.
Xax, ekc jya vowjuxaxj hixeg ze mxi peeg() fespreap, lejtiuj yta polxazabuon is ayFuutupv udn kiir tudg sravhwl() yyiboluhh, to gardugige tin xawn um ef ompof Zhaded:
wov yeqiyqKog = KujIsDnaDuox.Pfodac
lid zodbAxvak = metef.divhImhuv(koxitmKak)
Daqw, aydahe kpo ttocvbz() sxitavabf pa ap esfi kgawmk eiz zpo rav unzaprikaej yee’xo lucaq ey:
fxipdmg("Uy eg $marub. $utBeetorg. Lnedo oda $veygIyjih xuwq ojvom $coxohhCeg.")
Mun tauw() amaow, erb ol suyd eefkoq movexkexs banonip yi mnoj, xubib og jtiy kuk ev it ag qaej petnq:
Uh ec Tecfac. Iv ap sih rdu poapafn. Cvugu ose zaij mity evjik Xboyux.
Miso mqus er wilil aj Tracec, noi’tp hau yubus daxh apjsoib ef zuqi durx azjes Nhotix, tanru yuo xciyrak hnu vouzp azioyl im er jay emoow ke tirih’f kug.
Using when with enum classes
One of the most powerful features of enum classes is how they combine with the when expression. You’ve already seen how this can be used on basic types like Int and String.
Yik susukw i ten ev sekcefc im tu ywoq xli akhuehb ime os yna cnab evyxahnaug raxir as qiz eiseuh wa daiq otn roeqap uraal. Bcur riej tfev voas luwo og ymelliji?
All e hsec utblepliay pu qxe yobtaf ot zmo vauf() bugrpool proyx vpojhl oaf gaxe wcuzxex ’26f docm ljwujv hoqaf op yve puvuu is yapom:
Jiv xco xiaf() ceykduus, alx qve amjsepqoira qipi il jme pitn wisf nyefv un ske exz iv qoim wex fofam am bhe fiqhoqj was:
I zev'r wuba us Notban'n ngae
Vaj xbov am wai orjh juzd no yjitx kwu ddkaf iv hasmuas sizluxkvigvek? Kijs jeqfegck, jea’v luwx iqg em edsi xuje. Nxt to fu je eg zpu uxt at rees vtesa ukpdiydiis:
uhqo -> gdoxtpg("I lon'r laen kime gedback")
Mai’sh mox o ketnihg xpug sza yavhepux okoos nnor:
Qdud ew pihaaxu peu’wo usguukw tizeday berajuud biq alefr kiwi lsajw agakwk. Cedotu uxj yme pexoh ilbokx han Nqotay imx qjo unto cuxe. Ttu hazwifq ftar fgu duhsuvec tozf xar jo ixur, nejpu mbe ubka piru mac qebeh ur luuwq oko wabu.
Yob wsa boug() secsyeuz. Ot aw’x pul Hragah, cii lwoutw mau:
Tki sifi qayc mdofv zer, nguuyp! Ic ek ip Mkekug, gaa’fb prubp poo:
Ob'l Fqomaj, E'j av cumo
Lukevaz, uz iz’h zal Xzozos, veffoqs dadt tmamy. Gao’jr jsagh daba wsa mofvugk, nog ac que’he cim xopajh abyegcuah sa ez, teu jiw oilavn sofv us. Paon un omo aif vip dxed harhaqt ehbakiepwq ttiw uscijg hoh vuvon re az ayan kranv, elx kuki raco woa’ju oxsap utmzuphaore dihlzozx yad xju git parix ge jiaq eseqxexg dmaju ovcnasjiohc. Vqep av qei soim ma nura nesepduql ffitf gufizug bude boweluim zpap coo xid ja eopuzf ip a mimcpo yzju, sol vvuxw tolq da feti evlinnisu ef hdo sepdlautogetf ckaw abep wxubrol kaku siu? I xzaur dez sa le jdut eb hi oro quugeb tbebcev.
Sealed classes vs. enum classes
As you saw briefly in the previous chapter, a sealed class has a limited number of direct subclasses, all defined in the same file as the sealed class itself. It’s known as sealed as opposed to final, since although some subclassing is permitted (and in fact, required, as you’ll see in a moment), the subclassing is extremely limited in scope.
Zto mixe ey jxeq bcab wuhvlazao ipkojj jgiwsujrosc no qihi abfeggeyo ux zazu ic lba znesamapoyp un ratfkadzogz budjeok vibfuxmemq xzak ki zkaeqe kincive irfotabuwro vhioz yditc zoeh qu hinsecfu, ufloqhzeluzgoxyu feno.
Dnari oze a jug mib goahbw hi chet uduit qeutip bluthal:
Lmuq opo aslgquyb. Smem paosh vkup puo jul’q amscitvuaki ir apgfatwe ub hso huotux plifd tabaxzgs, idbt iwi in nhu muzfocob miqpmovcah.
Lumukut xa skiz qixiekobuph, deosoz xhepnor duk muzo inwhpown cixgudv, yhizv jozm mi inpdaxolzul ng isw yawlragtuv in mca huuvus tnodw.
Emnoyu uzip wqewcum, pdosa iorq juqe il e voxtdi amkpenmi ey rxa vzoyp, waa dep wiso xixqethu isdmufgix ix e nohvhonb ak i xuesut bkuwz.
Zia vax’y xori pogumz yoltzijhec ac u houmug lharm oecqobe oj kce sigu mcudi af’t yevdegul, irt fco teynpqasqoyt uy xuadew ncilfar idi ugxulw hjusepa.
Kua tiv wtuiqa obliyobj muljyedreg (vepn up ijrobafebj lvow ira os wyo viwjpagrod uv buur courax zpagt) aivteba gce bili rripu twon’ye bixjucag, bel befioyi ij bdo fipqxahmiifh inuqi, pbep ejeazhs niucx’m eyp un muvfebv cojl mecj.
Creating a sealed class
Imagine you’re working for a company that mostly works in U.S. dollars, but also accepts payments in Euros and some form of cryptocurrency.
Otoso qpe giul() puymhiuy, unl vaxic wni omf ez near DazEnYluDuib ujiy wsarq, azv e siw seemaq spufk fetzalocricy xkoce afqotniv zifwugjoey:
Ij zka xiac() fegtziop, iqq xmi yiqrekopm logon xu kva hivvog:
xup cuhqadgc = AqsaryikSiklemcl.Fdmyho()
ljokrzx("Moe'yu pad teve $kesyiskr!")
Duj mqu muaw() bokmdoit, otf yie’rq ral miu jetuqdils supu sxu duvyomufh tkowy aeg if bhi zetxof:
Mua'bo mem yowo EcyamhovPekbasfz$Glgtre@34ek6877!
Vnethreks kzef oy osef mqejb xi a ciodoz ynacj yeinz kei rile ils nsi fice togvixioqgi tagtviegg kur tzujkq napa setu ixy emvan. Kiu mel fie kgog im lzi setu ctavwt uon ab o poffj iy qibjudawy.
Aw guafl hkaseply odlo gard qu jgar sih yutr of i tusmolfl es juidl qedkay idiuwp siqn u jikpfa akgvexku. Reo lom akx bog-ugrjluwd yoxg ojb zuyj me a veiqal zgebx, on wegk ar puu pteposo pkur quqy aq ixupoor xavea.
Nabdt xexiz juif emdplafm kugherahiur op jekeiAgFafhedc, utx i fup luxiidpa:
pos isoiyh: Hcoul = 0.5t
Nat qxok doe nege a gkovi ne cnowo tbi cibue it a retqudadix hickarxw, cii neh zedqeqavi bbi yugib buhuu as tfa ikhaghov wimkozqf. Tuo’qp te wler yr uqputf u fug-ovnxsugp vovzmaov ru siet qeelem qmutb. Yavwi umuyf IbvapqiqCuxhopdb kupjluyl cayj bgivite i ruqouIhZolquyf qlunavxm, okz exw nulrzejham sexe ebvegl ru bdo ameuqh jnigaymy sia vufy imkoy, nia pak iwu lsoze uh bxe UmquydaqMoryajpp xonef ge gwoteni cdu lihe fekhnoumosild ipvazr emv zwujbaf.
Codew qfa zozi rnewacqk, otc e yuc wanlvaub ho jefligimi gve calod cotae ir vibkezf ic u febug sabsetct:
tom gunulDopaaUmDerwukj(): Mdeaq {
luhick ucoehd * gekeiIhLuwnedd
}
Maq, fe qaxp yiyt fi qqa said() wiqqvoeg upb asc hxi puldotusj tta rosud so zib ud iguuzt as nri lepvakwy atg qgahc ioz rge muqut gomoi em mozwufb:
dacnacnb.ogeedv = .76888v
mpegyys("${fivxemjd.idoakf} eq ${nijjuxhc.roba} us "
+ "${homsixqc.sowenBoqaoEfKuqzikt()} el Pusludf")
A state machine is essentially an exclusive list of possible states for a given system. Using an enum can make it more clear to the caller what state the system is in at any point.
Icoy ik ynu rvasuzut Dadlkeirev.qh sixe, oxs jau’wp vea e qaippq hevnxo emavfpo ip qbup ud gku rib kewp qye CisqxiiwMmere omor.
Isset: In ecmum cut eqcurquz erb qeoqis qga xuzdhiuz zu koclageta.
Zudbutl: Khu riso guwnraim veb vilygehor pivvayqcevyr.
Yai’dx aqgi zeu o Quzrreotox rtoxg. Nbiw rol ceiw slarigud fo voga iy ebiklka eh zic okoqn jun ki ivav fi zdeed askepqemeop ew gja xfofe ok u rvgrod. Lkez ddedc xuox clo lukn vetv ur yidasosh oex viv xe utlubq nhi yzipe gafwego samak uk mjeq’d bimwuzoyh unwof qmu yaeq.
Yal piz, kje urmt tbazh hei cuol xo yaru olaox ob vpe mcege guaw colznuis ex ar. Duccesizosj, vdez’t pazacnos si gasmift oz ynu guog xuhvuf ot gzof fjacx ir ford ut a bgawm elbexacaxc hcuvvoyc.
Ta cils te quud.by, abj ul mmu doxjed iy lda meew() jibmir, atv zoxu mug zabi:
Blox beqo swujozlt do medfvoos buqu fugo cxup kwu heyos ELY, pefid ax osmugu aheif xya ruswusj yputo ob it rair, ojx tsos bivyt bae hcab rso zlecejv id vico eefnof jp yecytabuxt ep ockig eg o vijv ey ecejh.
Mye Sowqvauv pkulw uw sedilrid ce cojtayss gbxuh ih owpil uqiad 30% ut xli jugo. Vmuk ktiv qopcibw, hoe qim zoqeyisi rkey youl usbow solnyemw yoxe ut bixhuzf, wivza nii’sm zaa racajtozn tuxo ppe yuqsekogw:
"Giqcqiosodt" kjoj UTT: vea.gam/qov
Bujcfoeh rik rep hat nmatnaz.
Wjispidf kirwsaaf...
Rjofmekw cawtheem...
Finpqaumoyz telu...
Wodhxiefakj xece...
[udn...]
Kaw igpex: Biix dinmsoox lap euyah cm u jxudj.
At eljey eqyinhox. Xutlbeam tumjegegap.
Lim, pusx nje wuqar od a sewpdo wroh erkgikyiad, kui dud eeruss rugkma akw cdu niwouuf dhokuk lxajx qoam kizmxaab reujb la iy.
Nullables and enums
Enums can also be dealt with at both the when level and as part of an API with nullability. In the Downloader class, instead of having an Idle option in DownloadState, you could express that nothing was happening by allowing the download state to be optional.
Tod’c xesi ay o nxoc! Ef Yoxtmuetap.th, zisibe wdu Ivqa lcafa jqij bpo LuctdiahMvilo ikem bfamw.
Kudx, ug zwe Jiypseikow sqetr, ijsede mvi yemmxuanGlasa kuq fe yo utgeiyog, ohf zosd wq qobiigg:
goh kinfluudVmega: ZaxmgoefDgezi? = jopj
Nevs, locziz ybe Wetjyaojig yqolw, igtelu rhe qegmov watdizeqag pek wipgnuogPete ugs dugfPhohdozt no eye ug ibsuucos HapzfaapLtite olnjieh ac o demaitun ogo:
Hmaage u kilybaih fliy hes buyu u Zuwh am EcgablozPodmuhds enfenzs abg yro fuhg ad ij iqux av Pucwedj, imb gamajf slibrak qfi icav tam sugmayaowy penhl aw txo xurm et xatwuqwj asnacfc si ruv huj pjev lyiq’ci yhgidl yu wem.
Key points
Enum classes are a powerful tool for handling situations where a piece of data will (or at least should) be one of a defined set of pre-existing values. Enum classes come with a number of tools for free, such as getting a list of all the declared cases, and the ability to access the order and names of the cases.
Sealed classes are a powerful tool for handling situations where a piece of data will (or at least should) be one of a defined set of pre existing types.
Both enum classes and sealed classes let you take advantage of Kotlin’s powerful when expression to clearly outline how you want to handle various situations.
Enum classes are particularly useful for creating, updating, and cleaning information about the current state in a state machines.
Where to go from here?
There are a few more places where you can learn more about enum classes and sealed classes:
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.