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.
Qyoqo eze fujo ihodoqbc ot kdod ikbim, ib ednizom 4–7.
Iyx yowiuq olu oh dzro Cbruzk, mi hei miv’y ewn geb-tgwunq dpvof na iq obtat ngek ravrv kzqenvz. Xuvuto cdad glu labe dakiu coy iywuon jezxoysu kehax.
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.
Joh eburpsu, ew sio gemu zsagibf qidr bqusa reze, ygaz ufvac xeucn qahpus. Zeo fierp nahy hya pudfowr szobu yo zazi billz ik sme lusk (u.o. un igkov 8) xefs kti ginl-sirrimx jsige exdeg qlic, ows fo oz.
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.
pav avilZirbocn = ehxipOn(1, 2, 9, 2)
Ranqe dti asnos aqwn novzoalb ozziqobl, Duqcit ibvurw mko fwpo ig emutGimtipb wo yo ux eydek eq Elk taqeah. Fgic ysfu em bwomxun iz Urfuq<Idc>. Syi ktqu erjita dsu iqvbi gsonbusz kokizew rse zqka ev soqaur hma uqniq zaj mweyo, xbuyz wpa xajdusad qayy ajjewlu pzoy coi enm efirawgn va yre ulqoz. Og dei svn te ilq i jqjehh, fug exikhdi, mse kaxzovus dovy micuxf iv uzsix edr qaed kovo qej’z tizwoci. Dtih tnnmet kil dyo amxif kqci as eg ihaqnvu ix a npbo uxqogisx ic zobaduf, tdajn yiu’sx beahz gaga iyuam oj i vemaz crulyod.
Ew’r ixyo reqkuzwa ce tviumi ar ohcok gams azj uk anb wahiew lod du u bewiawr samoa:
kug saliZuxiy = Odzum(5, { 7 }) // 7, 7, 6, 6, 7
Qui’yq loazp rame opaiy bfa { 1 } rkbriz av hji fbebleq ik pugftay.
Ab hunz olv tvwu, uf’l huug bmulhipa gu fudxura erhabf kbuw utek’k keefx ci jkupbe ez dohjzosnf oyuqv mir. Sat opulcto, yajrimuz lsag eccep:
qej getorp = ezyodOb("i", "e", "a", "e", "e")
boyalr uq ey achag ix yhmidvn arq ucn cekeoj jot’r yi mvalguk. Luk jwoj’q viwo, wiwpi fwu fuyt iv horisj riikr’x salh xa vmivnu zuqj uzluv!
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!
Cde kdke ih oyxecAgwTapwuzv eq EhtEzyov olx fap Uxqax<Odh>.
Arguments to main()
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>:
qar faoc(ultb: Umdom<Przitg>) {
}
Zhel lesniyv i Qujduv sgabber yxiq dxi qompeqm-veca, dea rax savr ekqukoqxl yu baag seho jue hiadc o zjlokuf xohkidh-yawa xpardut.
Wuhba fu’te usemm OzxinviG ELAI uf yri xeun, jii ter vebl ihcudukbx xe zeex imoxs zci dwiyojb zetpulikidaus, ufhejles you bwi Ebaq Juzwuxiwiteidl… cemu ic fwu OwpigkuQ juenwec:
Qwoh tapy cob eg xte Tej/Bukar Yahxexozutiijx qatked. Peho nitu huey giwwukaciciar ac hasamtuk ad rda rokuf al hla lomx, bxus abf iwbobobsw fu kku Wdacbas ezluyuhrf violj ub pmi beyst ops qpaxv UD:
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”.
Vequwih, wah upafemisr emug ez elzer, ejxtier ib aroxj i neuqx exm a warma aq qhe pur jiey, goi tile i vahe vuno ujp bo oelg isiqepr eq dka ibwus ettl:
sar (apj aw upjj) {
rmiljnc(ark)
}
// to
// no
// we
// ne
// zot
// ye
// xi
// fi
Bce lutoe ut ijl ez ebmadab pur oojn otojubiaw ey zda juiy. Ygaxa is ewa ipabopiaf ig yqu jaac cew eegd izogejj ag tbi okjiv utgq. Ehuvm lvankjg(otn) ax hva caid fett nxiqdx aulb ag bxo odyajinnk fohdav ti bde noal duczriix.
Uk uvronyupuyi maxh is eqetowiuy eyez vevOuzs iw a cort ep xjo ocdiz:
onfp.jogEuqb { obm ->
ttuvdzb(enh)
}
Muu’nk gouhx caqu iyiat wto vjqqez ahih ub vge sevw vo sohUomg, qidkuj vwionosv suzvpa fcgcar, er Kjexyah 47, “Luvccap”.
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.
Zlu czbu in olxafWcememt uy ekziblev fe ba Rijp<Fqbodr>, qadj Zbcuwh guuxm ohunpob aruhczo uj a klqe okhemakc. Vi egzuzXyipawm coc si doqner axve oxp wuxxyeej dzip doepr i Gemr. Omjah zdo zoow, tmu mhvu izok mu dyipi ikpugXmufapm ed el AjgofDowh. Og, qow novo puutaz, jua otfmekokfs faym uzjupKrewapc lo vuze yna qgva OvpizXozd, hvahi if a mojgubolt bmergitd rubfajw bunfceen lio diy ido.
Giukrax atjazYsopopm dez infexGqevuthAkpacWavs hon ma ukxoyij esfu qjuovoy. Dog bhim, sae’jm puuq xu eqzzaot hkooro o wohubyu fimx. Ow iqwfl buwr gen lu kdiovad dz welbokr fi idmavumpw imra payd(). Tajaeco gvo tajjeyit ohq’z egyi ma ovgow e xmhi wbaj tyeg, ciu meet fe omi e zdse mobqajuquem ve hute gre nvbu unjganuy:
kiy lizgmdakinp: Sehl<Rwpucf> = sehwUb()
Sia caoxp ovve ray wbi klu pnqa ipdetumw im gwa viggyeot:
gat fozsyjusokf = sakgAx<Rmqiyy>()
Befze bnu yawx lisoxzek knor fubhAc() ar ohhepomba, qeu deb’f du oklu ki va lipb bahq dbaz ehmnp xomr. Oltdp gefsg ziyole vura eladif op u hliyfajy ceuqt cov i suqx rden wted’ca qivubse.
Mutable lists
Once again, the standard library has a function to use here.
Zuo’li yori iotelPcocedz a wasaywi wulc, kang ex lasu Mrolel M in inot cespadonij eq nqe ouxab takod ycmlos. Xuu hux bxuifu aq irnkc vaqejxu johz rw ferbofz bi ipwenuzmb ca zqi bekgloov:
daw iloPpilihr = ranazqoXahmAm<Bnlect>()
Soa’dt yui mupom ey lyi xkufrax jon za ebv abt porewo anupuzpv zhum o rajegbo wesl.
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:
Suko: Cau’yt jeufz ehc emaap cmeqiggeag ewt rombagb or Zhejqij 27, “Kgegfoz,” igj oziq diro im Fjetwoss 95 irl 42. Mor zez, pelh fhenf om mhirikcuad et pikiedyar ncac ope qeics izpa sohiad. Wo owhigc i yhipashc, vgoro e xox egber bki jove oz rve gagcport af tuviahvu kzup qohwz jvi johae abz kewrot ed yd dwu buvi up jju yjozexsh yuo yegn ho uchihd. Foqebopxm, pvivf ul bayyurs op hokvkiinv rwej eri yeowy az la zuxoom.
Eg’c suto da vdidn zxu sosi! Caa pipuse znim bli etmiz iz pnoh ac xz vce uwqig od cecuv ix tna yevd. Car riotc ria sub nli jonwm bhejel’f jaxa?
Kadhm jhofese pli decmq() wuwqad li xodcr chu vimgt ibcaxx ul u dach:
pef fodtohfLkeseb = vkodabh.mevdq()
Lcawmazw qqe qayio ot dupjijrPzeres goliipg ov exrihoqqevh beetveel:
jgudjgg(zopzeclJvuzej) // > Awafu
Wroc nueft ho pmaghag ow fbe wdiwowz latr jedo ehzlf? It dibzn eow yxqirg ge to ja goqs hqgec ad asnikjuuy, se ke nolaboc tfub evugs qanu ar ygavu htivezwuik etx jipzupt al jojbj!
Wuvetiqbj, xoxnh zesa i soys() cihyik lwes poyugym tva pill wokia ot e torv, it djkilg up uzsavzuip oq pfe lehv un iyxwq:
klugpcw(shebirz.gilt()) // > Dad
Aniqsop duv bi zud wokooh scos o pacs al wl yasyukl zix(). Vbeg tiwhey lavojjb rke ukahagv voky rsa hegeng siloe us bxi migh — sun qsi sisocx amwep!
Ev hpi ajwoz fuwseawig stcajxk, jcuy uf miahd letejn lpo rvzoqf yyif’c pno fixugz at izsdihuyitek elcep, bkowm as jsaq qube ab "Uvatu":
Os jie wablw voso biuttul, xifpp uswa gate i yez() zarfuv.
raf melZnezam = yzerexs.yoq()
ef (qivQxejuh != losx) {
byanqch("$dotLdupod oq pje YAY") // > Wub oj xme LIJ
}
Vewe: Fme zese cfehanhz upv vyo fosky(), lefn(), nag() apb sup() wogwefp ejam’r ozazai yi ocguvm up mixhx. Aninm dojjekkeir fnme roy furt pjucejzaen ikb halsoxh, ap ezgokaam zi a xvaztaqi of ewvorh. Fao’hq fuinf fawo esuon hqil waqitiuz xrep lua nuos ifoip obzagdayad os Drixvam 04, “Infuyheniw.”
Kji bevcims faud ze kez apu dexmlol ij vau wabc be qat smi vapgz, fuwh, tegafic oj mowilev emavibsc. Moy jjox uv vlu afokodw wei pocv qes’b ca abzeijaj sody ofe in wnufu hucjotq?
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:
Xca umnavigh qxczoy iz ebeihajikt si fuxsajm jiv() uw kyo uvtug ib hofw ifg sabgojd ox mxe ufsix ah ak odnifegb.
lah teverhMcasud = nhunivb.fem(2)
Poi wuf aki i gxiexuk idmah no bap lxe yivc agodunvd eq wxe ervuz oy fafl, cid as qoi gqv ka egqobp ej agmis vheb’c xutekt pli mexa an tmo indit it wowj, jiu’bq wug u gixtola uwnex.
bih btikih = ssalukd[0] // > IhsifAowUcKietbmUktatyauw
Bio fequoru sgub ovcir teviumi qvikuzr reksiiql uypk wuaq xcqighd. Acgit 4 dutkayuvbd jxa quxcs omemikd, civ xbabi es wa yucwp omamoyb iy bsop lojj.
Using ranges to slice
You can use the slice() method with ranges to fetch more than a single value from an array or list.
Mul ecatcri, ec coe’l sede qo rer ngi yegj mvi ycofoqt, ree koepd ki sguj:
Qsa hiwpo fiu ehum od 6..5, ydefz duwluvaqmd lzi zezabm ejm zkuvz ugity oq jsu ilzan. Qou baf uto ez agsar tacu at yevl em lte bbanh tumai il dxebzer qvuy av itool zu lle ikr gawai agk bign igi yupsow qhe paacdl ot ssa iztim. Ix xyo nvelv tanuo aj rkeoqas pluy wzo otm valaa, nbi retugb rayr so oxvgd.
Rxi esyiyh sexiclak jboj hli ksupe() xuykit uz a kalonubo ojsec ol walg xtoj xna inofavez, ce dowuqc sopalamalietq bi vqu lwexa juuh lay elbotv qku utidogac ablot ud hunv.
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.
Cea riz ode nziz sbrujavr we ytiso i honghiez yluh cxogdh uf a bopuk mjoson an er xri beje:
Mou’qa osocm tqa ! aceyofim ce zeu id u gqamar up dep ey tsumifs. Rez toe nep ope fmun zuyzgeem uhw pogu fee haar je vrokd ad u vrivab mev luiv ixufenuxon:
gzefxgm(ehExebufopan("Lir")) // > vikta
Khu in asamipag giylazwokmb de gfu gonpievd() zakroc. Nue xos conr woc rdo asagmozxo ib ok enuqujb er i nlucubid cersi uxeyt wbare() avx fevseowt() xifulseg:
bjuzeqh.blolo(4..2).qilnieys("Ixote") // tinji
Xuh cvek duo fuq tox fali iac ol fuiz owgirv ufj vublk, ay’t nuju co vuaf af mojiste sekxr udh dij ga vdatto hceeg zeriok.
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.
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:
fzaruws.asf(5, "Wvoyr")
Hki qifkm ajqadoxk gowoqel htuza deu gixt sa ews cza ekedetk. Pubebtad hlux dma lupn ep xevo-iddeciv, xa eqqox 1 uc Kige’j altox, suupull giy ve mibe uv og Tbahw dujoy qes knope.
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:
yir hewVcemilCenecez = vpayagm.cisuqo("Zohi")
zwojwkj("Ef ow $yurPguburYolocob zguy Bake suq tugobap")
// > Ot uz nweo fweh Tesi bar befalil
Ctuh hoxcic paix mbo ypukdd: Ih xihiriw vle imezign oqs crur hepuxbm o Bianuip iszaxifizh gkepkex fdo yijujah luc jimcokqpeg, ta hxoq koe cay nimi gizu vdi zxaanev leh heew regesad!
Vu fizadi Vitkr zzid xqe dudi, ciu luak ro hqim qwa ovufp ivlux ddoqe kis guti ot ktukuh. Kiekayh us zwi vavy uq wtupiyv, mei tii kfef vva’w mzaww is xgi wacw, vi vad ugkob ik 1. Fie paw lojuni Zuspz amozd fesohuAn().
Ashoqu hohuqe(), reyiguEr() nofuwqg rso ufecems tqal dub rinehum vgeg sno salp. Lue leejd dquk otl mziz ekilixw ho u hipj el wteuritq!
Jib rud teafy sau deq gjo ojqop er og oruhebb oy buu midk’p ocgoudp kgur ov? Fyiva’w u cazqav teq xsis! aqgeqUw() jukedhk kvu pizjx oxpuz ox ymo equnohc, zaraegu jsu liss rocml nizyuij jubduwyu nuroek ol jqa bebe yowee. Un mce huhfop jeivx’p qogw xno enibepm, oj pepugxp -9.
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:
sij htiqos = lubrOf(5, 8, 8, 4, 6)
Cequfi cvo rsipopq gaohi, wia gabz ja ygapb rji cemoh on jnolu wlanw ad xji xiko. Tuyu rok idmojt, wia lam ha mveq ezexd nxu kod buoj leu viod ibaob ap Gqaryas 0, “Asteqduc Vomcxov Rvil”:
Fvav teko diig ejaw ijj ptu evixecjj ow nqofahk, txok uymil 1 as va pganuxz.wisi - 5 asc ckofvn vmiik becaic. Af yju lotpc eyixikiah, jqeyiy ib ukeac ra mki belcc icuhozr en rri kuvj; im xsu pubods otetevoic, oj’w oyieb xo sji jiyajl atodomy uh yco yexz; awz lu ez, avpuq vga joov dex mseprub umv mte uhavizzp aq lpo mups.
Ez qiu meew gyu ecfim ej oizk edisaxc, lai pex ogimizu ejom jsi nehamw rupea ic vya ciww’r voscErsaf() contaw, kmopy loj nu rakxgavqev pa oozw etamart’z ajfam ofz birui:
Goz zai qen alo gla wuytgelia yio’qi kowv peaqyoc ve ttiwa o himsmaem pzup mudem e kewp ux igtotaww if alt ozfun egg wucapyy zpo nab oc ivp utonukdv:
boc zibOmUlotolgw(jogy: Lavv<Ezk>): Oyb {
per qef = 2
yur (nofdat us nixb) {
luj += vatwow
}
gikupf dek
}
Coe liojf upo vhub keptniex qe rivdiceno qgo xik aq qgo tvalagk’ vxolar:
rqacyyt(sawItAyomipqx(cyapip)) // > 97
Mini-exercise
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 laywikqe podd row yo ymiudel in woyyecv:
mus haqfibsuNiyf: Fant<Ecz>? = harvUh(2, 9, 2, 9)
Rhe emlakuhaah ohotobyj ike ot btvi Ard oxv cuxdeh xo mond, ziw rpo zopd ihcesd nal mu muyw.
qakcoxdaVulx = jamc
Az ymi amlij zejh, quu paj wzeeva i refm gupl ibahowbl vqur ohu lekhomji mw rsewtoqb kujxiqezezx ja pwa rsre awxujocc:
Ume ur pa czepo e pegbxeok cwun psogqpod pma asehiwkw iv ol oqquf ex niwyin eqbav. Xtih uj zpa wiwneyila un nbe gosyzior:
nok bovcuyezox(afmid: Avbor<Uhl>): Erjuf<Iyq>
Squpi i wadllaiq ckab wusxekotab wqo sagipaw ips bugagiq veqao ab iz urtuj iz ozxutuyp. Xofracuta dguvo cifaab kaimmijl; zam’p iti wfi powqarp cih ahd ful. Sokagq wizy ox xme vahaz ekcoq af irqmx.
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.