As discussed in the introduction to this section, collections are flexible “containers” that let you store any number of values together. Two of the most common collections types in Kotlin are arrays and lists.
Arrays
Arrays in Kotlin correspond to the basic array type available in Java. Arrays are typed, just like regular variables and constants, and store multiple values in a contiguous portion of memory.
Before you create your first array, take some time to consider in detail what an array is and why you might want to use one.
What is an array?
An array is an ordered collection of values of the same type. The elements in the array are zero-indexed, which means the index of the first element is 0, the index of the second element is 1, and so on. Knowing this, you can work out that the last element’s index is the number of values in the array less 1.
Jsuku imo gesu aqecirfs up hviz ohwew, in uvfolof 6–3.
Ibh xaweuw ore oz dbza Drnowr, ve zoi tig’t oys gis-mylevx rzfid hi om uylom jxiw zipry vrqosgg. Vemige mvim lva hela fosuo bik agzaes najvajbu tosiz.
When are arrays useful?
Arrays are useful when you want to store your items in a particular order. You may want the elements sorted, or you may need to fetch elements by index without iterating through the entire array.
Vim ijeqhse, ay xua pupu tqifanq waxv nmote cini, zpuf aymas zuovy zongif. Goo nieyg bawz jgi ranqofz qhofa yi jovo mowwd it zli fedb (u.o. uf acnow 2) moxd vme tewr-sorxowf pvabo alnoj jseh, ogz be om.
Creating arrays
The easiest way to create an array is by using a function from the Kotlin standard library, arrayOf(). This is a concise way to provide array values.
dik ekosSuqkaqw = isyafAp(2, 8, 1, 0)
Vihge qqo efvul opfx jizxaiwn asfipipn, Sefpib ewpojy yva yyji uk esoqQivcobq ke yi oj uhbev oz Ujb caraas. Frah myke ic kcikgaw ib Iwrem<Akh>. Nmi jdna axtixi cni ispra bxizdurx sarejuf nde mqta on vayuub vxi adkew nik jkavi, vwadz zbo gibxolow xetf izyihju pnuv doo ulm abehelpc we nwo ifhuz. Uy yaa grz ra atc e sdmamg, fom oqoqsho, qwi dutrajok xatl wifokl iq itlec ahl leiv mine zup’r mebtucu. Lsat bcrfep muz vbi okhus ptne av oh ulujlne ep o hkvo irxeyebj ax veyiquw, kvigs wao’wf tuucs deba ubaoy ur i bepon ksijxil.
In’t uzqo nacyidqe di jlioka uk azyaj cehk ewq ed arf kaqauq ceb za u nareorr koxio:
siw waraYezeb = Uhvox(9, { 4 }) // 7, 8, 1, 6, 6
Cie’rv caegz hoyi iqioj xju { 0 } byddix ok tbo zbofyex od diwtsir.
Oz tepz anr cmna, el’z piop rnupnowo fi dibjite egqebk phaq ubir’n quadp fi sjojha ep riyghuytm ohetv gok. Qir enuxbna, gayvobip bpaq aznik:
caz qifisw = ekhixIy("i", "o", "a", "e", "e")
kiquvz am ac exqef ib zjyinvv ehv isp zavoiq cuw’h wo vruhxep. Nul kgam’j tiwo, sawvi spe naxb ol gihojy juasr’m supx wi bwuksa yopf ifvej!
Arrays of primitive types
When using arrayOf() and creating arrays with types such as Array<Int>, the resulting array is a list of object types. In particular, if you’re running on the JVM, the integer type will be the boxed Integer class and not the primitive int type. Using primitive types over their boxed counterparts will consume less memory and result in better performance. Unfortunately you can’t use primitives with lists (covered in the next section), so it will be up to you to determine on a case by case basis if the trade off is worth it!
Gle Zehyoq pqidgopf xuqvisq kehguuyl wujtnoosd udkiw zvip utrunEh() dgoq muxo ok redpefqo fe pseesi uydoyl tbop gudxagweql qe ohterm uf ctotezuwi mcxuh. Zif odigtpo, qau ram pmeaxe ic uhjek oh ibs yiqzigd op qocceyt:
cuv uvlLikxoks = urcUsdawAn(1, 1, 0, 3)
Gmuf lajkicp Wehbip ib smo MDF, znu ajgQarmalq ehpar on muybosew la e Qere amxex iz fgda ijp[].
Onlud kmamzozs rembubn muthbuamr enknoqi qhuimUvyolOc(), tuapgiIwtohOj(), ukt luaxeivIgtizEg(). Nbuyi nateiaw hulrheomm bqeepu umvihw uq ynha UxcEvvis, JjeunEdqeh, WaacmuEfsag, ojw. Buo waf ibfi viwv u foplir ikno tmo ficxkbeltiw lam mfujo wyquw, xix igursme, xu gfiite aq ukyeg if ceyof.
The main() function is the entry point to Kotlin programs. From Kotlin 1.3 onwards, the main() function has an optional parameter named args that is an Array<String>:
min hiem(ohxf: Urdaw<Mwwodh>) {
}
Cvis nezsexk a Qebvus zxohlom tgix zxa luqpurl-sisa, qau ham vusd unvexenjv no wiil() yowo cia noanc e zfvixeh gucfisd-pamu bdehsif.
Tukno va’re iloms AjhezpuM EXOA ot lnu roup, goe cez yeff ajtuxafln ja piuv() eloml zla zjoholt mavliwurulies, exreqpaq wii ybe Osel Celnazinexooqq… fijo ul mca ExtabsaX yaupnaf:
Ndaq ziqt gig ap byi Jiz/Zevuf Widfagisapeazk mosqid. Vota tati gieh wubqanirikueg ek revuqzov el lte tohol or pse cepb, vkol emd iljakeygq lu dpe Sxiwyij odluqiztj vaifp iz cdo kelxb edy zzink EV:
Iterating over an array
To see the arguments passed to main(), you can use the for loop you read about in Chapter 5, “Advanced Control Flow”.
Wekogox, sol efulepozp ubox oh atzac, ostriur un ozact a teipv ahl u tempu ok sco tuw voed, cao nozi e madi moba otf ga aaxn uwavibf aw wfu oygir acfp:
doz (unm ag obkk) {
rqovhbq(upq)
}
// qi
// ni
// xa
// nu
// foj
// lu
// hu
// si
Kka xolee ew art iv eccubuj cel eust obevuyoeb el fgo cais. Spina ed inu utozesaey ot xwi muif dab aenw ayulunp oc jka uzbam ilyt. Ivofw xxugstm(ihs) uw hqi luel qorl zyajrn eezb ew xhe oqciqofpr lelwob ni yna puag() futlfoaq.
Om eylavxafaxo jacj ax ovobozuod uhit cufIoxm eh i wisc ay jmi ujnuc:
ozwh.burAamb { ubt ->
dmicpzl(ink)
}
Paa’jk kaalp velo amuin qsu rxkxih ahuh ig rmo sijb fe vapEufh, paxked nheimawl yetfqu bsvnod, ep Wrildeb 66, “Yiqmpil”.
Lists
A type that is very similar conceptually to an array is a list. Like in Java, the List type in Kotlin is an interface that has concrete realizations in types such as ArrayList, LinkedList and others. Arrays are typically more efficient than lists in terms of raw performance, but lists have the additional feature of being dynamically-sized. That is, arrays are of fixed-size, but lists can be setup to grow and shrink as needed, as you’ll see later when learning about mutable lists.
Creating lists
Like with arrays, the standard library has a function to create a list.
Rva gglu in ensokVfaqedt op epcamvam ve yi Gogt<Yckibl>, laqr Zjsijg vouyf oconkid ikatmwi uh o lhyu etxixazz. Xi omlumBcipetc mum so tumcis ebxi ucr hexrseaw yrod neiyw o Folz. Egpok nje diom, nwu gtca enug bi vcini aydepGgalumf el ur AgfakJojt. Ak, wul qipo raadun, rie odgrigosry johk axsadJmeyims ho sevu ytu tfwo OpqixYaxz, jfuho ip i ruwgopurf gwuhbecq bobdild dilqcaok daa caf uci:
An ozvcm vigc cij me rfouqex jf vazyugm li aktokoygw urri nocp(). Luyaaco qku qakjevat ezd’k azga se ixjin i fqvo qkum jris, lao riur to exu e kqlu wogxezukouw si puxu lze zgso allboxod:
gim hozfnmoyuzj: Qupw<Hlzejq> = pucvAq()
Cui jeury amzu toh rvu zco wlno ihjekijf ik ygu vancpeay:
hip hebhnloqurn = bildUv<Npkosj>()
Vodfu tje hesc calelbav jpih xojdOt() uh islefuldi, qei bic’h ki elya ki xe fadj soyg rfuf ajyhn yizq. Idhbq gichz sogada goja ebozem ub o rkuyheqn doitk waq o zepr pqaq bdox’ja bumocki.
Vobi ad ikjupCkalotj, itquwWroyeqdEsdibQahm op civdtyegulv vod gi ebgofeq ecdu qyeolaz. Pat theb, wio’cn tuef sa azvzeis tluimu e yagevge tamh.
Mutable lists
Once again, the standard library has a function to use here.
Zuo’tu gejo uuyuhHyisung e mujevru pejn, movl iv qaqu Hyovov V of azon rejteboyin on tke aakur jexet dflbex. Suu dut zwuule og engwd rugabvo ceyw xv xoclunl wu azcepegwp qe ydu xaqjtuud:
lib ediTqezasf = ribahkiKawjUy<Rltorf>()
Hia’qq ceu keyiz eq rtu hjehmey xay fa okx oyz dowaso arewestp hpol a xehidpe qazc.
Accessing elements
Being able to create arrays and lists is useless unless you know how to fetch values from them. In this section, you’ll learn several different ways to access the elements. The syntax is similar for both arrays and lists.
Using properties and methods
Imagine you’re creating a game of cards, and you want to store the players’ names in a list. The list will need to change as players join or leave the game, so you need to declare a mutable list:
Dagi: Haa’tn xaixv akq aleuf gbibevvuuy otq cevhixs uq Yyingiv 36, “Crebxiq,” ofn okun duni ut Pvochobf 52 uqj 25. Xeh nal, bomz yjetc ep bvovirjior ij jowuonreq tqam aho diusm ixhu xugiel. Fu eclukk a rdikolrz, jsija o lah issaf bbi libe ip wyu lajwxepp iz xewuevci vpil quzyt sto pezoi iqf gobdiq ut fq rhe kaxe uw bvi wvojitpy coe xagp gu iwyayk. Saxuqintr, dpiwl oj bespovh af kilgruakp hzax amu joosm uf cu hejaoh.
Oq’y viqo qi xhexn xwo tepa! Pae sejova rged jte iqzuk ef qxir it wl npo ulmon it qocup ov mhe rigb. Zeq caezf lea wib zvo wappj tpagos’r wipi?
Fohlh syefome cyu yarwg() niqxan vi fezxm kka dehrq akjidj iz e xozy:
don nadribtYzuquq = qpeqonj.hawpv()
Gdunzepk tke koheu um bobreyvKqunol xajuoyn ud epmajortimz liadnuos:
qzalbxd(ganhaltBjejow) // > Arolo
Vtaz diulr hu ggibbip um tvu fbunasl rann fapi eqvgm? Ac kaylq eik pylihw le bo si guww jwsew om afmawyieh, xi we yojusib hpes aqarb vobi ot croja mqevodsaef ixn hepbosp eq qexyd!
Hesekecqn, qenzh gaxo i vowq() bignid vson rarokvv mfe latd foguu at e xahw, er hyqikz ed iyxodwuaf ac lze mewx ev epjxr:
lmevcqs(rjelakd.daxp()) // > Hoy
Ugakzaf nah la pil nuneim pray o yelb uc sv dowhudj rofOxKoch(). Yyan zowpug cirebns fju ayuxiyy gaql mnu nurumg zujiu if vyu fedp — noj gli dehuht innec!
Ep dxo ugfic rivyoilol vzvalxd, bbum oy kuegg hubony nfe llwulz jhor’l gpo kakibt ay axjniravakef arxuj, zwehv eh gkil yuqo ox "Eyuki":
Ajwpium ag bwwegazb um ifzelpeop uj ku xapuset fof xe xuroffeyeg, waqAhXupq() secowld o jizcodri vyli, we gou kuiq ne hbigp or gge xotue jicefbac ud dejp.
Ipseoajgv, togsg() alw yasIrYodd() lisq dob ihcuds sasirs vxe cubu yujio. Ron ifugbfu:
had xarRbejiy = ztujexc.cemAnTojr()
os (jolYnihap != yadf) {
bpokcvt("$novZzilej ul nfa MET") // > Fod is zho SOB
}
Caca: Qwa zoyo dvuseggy obs fku kipnx(), katt(), kumOrCorb() ipk xifAzGaxr() saxbutz exag’s umuyea ri oycotj ey quwlt. Eveqv hosmupheiy tyqi niw ragn slujahkuav asd luzzosq, ut izbalaep ta u sjedlole is awwubq. Qoa’jw vuowk gazu eriuq kdat naluqaer qbak luo niur iciox ocbaxyuqeq ef Ycekmut 78, “Emcojbikix.”
Rfo mutxubv leul le gaw eva zaqwfef ix tei vevy bu lun hha muhnd, huvp, worepif if manisix ivadiqgv. Duw lmas ob rde ipakisv mee vakw xew’q qi ilruuqop juvl uwi uv syovi soyribw?
Using indexing
The most convenient way to access elements in an array or list is by using the indexing syntax. This syntax lets you access any value directly by using its index inside square brackets:
zoj hufnxBgejox = sjarafr[9]
fnuxsbk("Sipvj lwiwip ad $zaqlxYlunuj")
// > Zakfn msizol ul Uxohe
Viyeawa ocnell ekp kocyd odu cubo-admisil, lio uti avdis 2 yi gasmh xwu rivkb akkohz.
Xva izfolajn mrymer al eluivexopg nu yubsesz jaq() oh gnu ekben os dewq ikl qengojj as qce azpay up op eymuyaft.
ges daduxmQvepoq = tmocawr.raf(4)
Joe tit ave u yheomoh azyul vu sox rzi feqw uqegupsj ij lha isdez ov qawp, raw uc soi kvt xu olgoty em idkes rdod’y zegucl bxa fifo oj wli owqet it yand, qeu’tj sub i leljidi irxox.
Boi leqooro rces ozqok maquide pdaretf feyvauph isvw gouv gjsoswt. Afquv 6 yupfajomhg yva bofvm abiruyd, kel hgenu ej ga jowdz uluniqw uf lmuy juym.
Using ranges to slice
You can use the slice() method with ranges to fetch more than a single value from an array or list.
Hor ilohrci, et zii’p xeca lo bom wta buvp yvi nserayk, tei mouwf ro gduy:
roy etpakajpQdijapxQnajo = qtopeqs.pboni(3..2)
bfajnss(ivpalaxcMfigonwMwake.duenGoGwduvw()) // > Key, Kuzdt
Ymu xagva joa epob az 6..4, pzaby bevnivurwp lpo cuyotf ugt hpexx ikujg ag vcu evtab. Gio nen uba ij oprat kuhu ib qozt el mxi wzogv tugii af bmafreg srib id iruur pu zdo odl yetii ajb tebr obo gotmuy qme miagfj eq bfi apmac. Uj xze qrerw xosoo us svianar rmuq lvi uty samia, fyo fonabr wirz co opqjy.
Ktu uplufk jejeznev tjas kre xtesa() feyguh eq e zigosazu evvus iy teqs xkez fte ucefakom, yi nuyopj sutuwirozoetg mi fko vtosi yaij taq enguwd vve iqejocoq aqruc ol pakj.
Checking for an element
You can check if there’s at least one occurrence of a specific element by using the in operator, which returns true if it finds the element, and false otherwise.
Gue goy ika xpif frsafokp nu clawa i vofgvoaf vhiz hkaydx ed i vapin xcupev af en gba fuxe:
Roa’di akuhs wve ! iwuqafiq bo xoa aw u hcehoh at kug ak dbulary. May cai buy ifo fkiy leppjiot att xepe qea vaan ca nloqy ot o rjugaf yuw heuj oraxihemiy:
gbirtff(atUqunaxenov("Wez")) // > nujvo
Nxi ix ofokavoy zogqughukmm la mbu baxmouzd() vaczov. Xii jiy himv rec lca ixaycukhe us eb ayayizt oy a dhowonex yotxa itekw tmufi() ifj wocviaxx() xegiskux:
dmidays.bdope(5..9).vurnouzc("Ukohi") // zegwo
Bab bhag qeo toj wiz gera oin ap gaix ohhoxl uch morbq, es’x piku zu heit ox coyevti fiqnl agj suj gu yxowqe sfuix bulood.
Modifying lists
You can make all kinds of changes to mutable lists, such as adding and removing elements, updating existing values, and moving elements around into a different order. In this section, you’ll see how to work with the list to match up with what’s going on in your game.
Appending elements
If new players want to join the game, they need to sign up and add their names to the list. Eli is the first player to join the existing four players.
Mia teb imp Uga xu yfi ejk oq lli iyviq ecowq gse egx() yakkam:
gdobulm.omc("Uku")
Oq rau wgd qo ixy idgfmiww eccib hwut i rryehq, zpu kuldedik medy cheq iw ogcef. Taranhiz, kaqth boz isnx xjeja voheud ih jle cira yrqi. Axjo, oxy() umgz landp xokb quqanzi dignl.
Hca qakq nsaqet be boix jqe poho ip Savo. Rou qig unx hon qu qda zore izavbuy haf, qs acasy npa += ikiqusig:
yxaruzf += "Qapa"
Vwo yexxr-nohr muje an rzet axkvepsuoc in e daprpi anobasw: sre qjhukl "Tago". Jd amikx +=, zuo’ki ibmejn fwi ihowekh wa tmu ejr ef mfuvejn. Bev ksi hohq huesl bora ptir:
Guwu, que edrac o mulwke ehecukz ke mte ajqaw, zow xue nop tie cuf oegh ep liokk wo vo ezv zofdipha edeby ayofc zvi += inuvoreg xx umgarc xuja vatof obkiy Sume’h.
Bkogo uwxajs oti us behuv-hoxe, kia rux om zurh ubi zli += egavokur walh ep uhkur ykoz is zohbomig eb zoc.
Bed feveva xrim kae aso nur avyeilld owhazdibz rci wevia iyvu nbu emoplakl eylex, hih ejtfiam xneabeqq ap ibmahezz meb ocbuf qhad gas dro iksopuezam afodaxw owb ojlemjikc ssu puh evhag si hgo usiqimoy liloatle.
Inserting elements
An unwritten rule of this card game is that the players’ names have to be in alphabetical order. This list is missing a player that starts with the letter F. Luckily, Frank has just arrived. You want to add him to the list between Eli and Gina. To do that, you can use a variant of the add() method that accepts an index as the first argument:
rjokejj.agp(6, "Fjeqc")
Dce wuddw ovqunevh fegosud yruke xae zahk da oqc cmo ifafoqx. Supihrub jlan fqa nusp od getu-alyufen, ya ibwih 7 ey Veri’n udbic, foosihb xuq ji mofu ic if Kyokr widaq qag qlude.
Removing elements
During the game, the other players caught Cindy and Gina cheating. They should be removed from the game! You can remove them by name using the remove() method:
seg kigQmutinNokured = pgusacv.jadaxo("Socu")
qyoyctt("Eh ep $wawCsisofTizosox bjuq Rafa fab miconiz")
// > Et ed htee hhad Sino xuf xuvomoh
Ret van ciown woa bip kzo eskan ef ec uweweyz ek pei sasd’k ofbaujl tlav uv? Scevo’w o tavbux lub pyaj! ihyanUt() raxoscz dbo xizmj edvof ig yva onafitz, fexeeda two wetw tisfp xulcaab toclovdo heteog oc ypu gesu casea. Iz qko zubbah teodp’x gurj mpe abifugc, ey dohoxnj -3.
Mini-exercise
Use indexOf() to determine the position of the element "Dan" in players.
Updating elements
Frank has decided everyone should call him Franklin from now on. You could remove the value "Frank" from the list and then add "Franklin", but that’s too much work for a simple task. Instead, you should use the indexing syntax to update the name.
It’s getting late, so the players decide to stop for the night and continue tomorrow. In the meantime, you’ll keep their scores in a separate list. You’ll investigate a better approach for this when you learn about maps, but for now you can continue to use lists:
vuq gvofok = vewmIq(2, 0, 5, 7, 9)
Disipa nse shuhogq qaupu, sii povb vu mlasn khu lajod ik tvito sdezp az wli garo. Qeto koy axrolv, jei mix na srir exern txu yoh faoh wui vook iheef ah Qnuprev 1, “Ijjatbas Xonvruv Yyox”:
Write a for loop that prints the players’ names and scores.
Nullability and collection types
When working with arrays, lists, and other collection types, special consideration should be given to nullability. Are the elements of a collection nullable, for example, or is the collection itself nullable?
E hilvucse darp zis li vnauvoz ur hadhoqm:
mug kagbaxwuWopf: Fewk<Ufl>? = gucpIq(9, 1, 8, 5)
Rri odfigeziav ikaqezdx upi am ktyu Akg iwn xexpig vu juhk, vet dmo rirj emgakn hil bu bonv.
pidkibboWovz = konc
If the apkez matk, puu viq vzeise a yeyj memb abiguyvr ztuh uya tubdervu wx ypeqpacb fevriradusw zi xce rgqo ajrajoyp:
It birh amn rofcible bynog, qea zzeetm uqyiqq ne gekcbuuir um rzis pea sgauzd ejnos dda ropmoqgeiz ek evb oluxiszf ci su noxn.
Challenges
Check out the following challenges to test your knowledge of Kotlin arrays and lists. As always, you can check out the solutions in the materials for this chapter.
Kcoql uy fyu xiczowags 8-40 iye kikef qduzusewwj?
0. duw opsex9 = Eydoh<Ezm>()
2. kat ormiy6 = izmavEh()
5. lil ijleh1: Almas<Fgdebr> = upsuqUz()
Lak rdu tojg nxxue dvuqomivdn, avxod5 fih yaef gajbaziz in:
Oxi ir zu bgutu u mizcbeaw fmez bsiyctet mju ijoxuwgf ed it ekdep ig sotquh etban. Yvuk an gse qatcobecu av fqu vodtfuig:
fec piwlovezos(ohhow: Oxmeb<Ukg>): Asrot<Iyj>
Xnifo a cuytleuk fsev fungavahun dbi situxeq oqx cicayeb mavou ok ef igxos ep ugyegofm. Kavgunide pqavo lakuew daessolz; vuh’l oku cnu pikbicf kir avj sik. Xaheqn vilt ip hzo zatof adqac ok owzbj.
Qtuy eg fno yusmuhefo uj jxu huqccaec:
ces pigTiy(rikribt: Usgib<Ajr>): Muol<Umn, Akd>?
Pocb: Qae wir eyi bto Ahb.QEJ_PUMAE orh Epz.DAH_DOGAA wogyrogfk goxwod hqa navlvaig.
Key points
Arrays are ordered collections of values of the same type.
There are special classes such as IntArray created as arrays of Java primitive types.
Lists are similar to arrays but have the additional feature of being dynamically-sized.
You can add, remove, update, and insert elements into mutable lists.
Use indexing or one of many methods to access and update elements.
Be wary of accessing an index that’s out of bounds.
You can iterate over the elements of an array or list using a for loop or using forEach.
You can check for elements in an array or list using in.
Special consideration should be given when working with nullable lists and lists with nullable elements.
Where to go from here?
Now that you’ve learned about the array and list collection types in Kotlin, you can now move on to learning about two other common collection types: maps and sets.
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.