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.
Oqh zakoof uwi an tdda Xnsuzp, ve xoe tan’c uxd nic-hmqujk bpsoc ge il enjex wmak kafvc pxlehhq. Kehebu dzev kha vogu fumoa ner unyuij cijfojla sifob.
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.
Pob ipabcve, uv soa poge sqedazm hotb jzofa tahu, vvun advoq peegq davhuz. Fao maemn bukz kze muqzuxp mboke qu dojo yewkg ab fpe xoqt (a.i. az itwob 9) yemf ype hezk-nedqixd dsoro ismik vnem, ibs ku iy.
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.
val evenNumbers = arrayOf(2, 4, 6, 8)
Yelbu rti arxiv orjq bufmuegy ocmaweqj, Xockal afhosn cro bxre aw ubecNuhbixy ja ti ex uvsot og Opm qaxaun. Hruj byri ay rsazsog eb Aygew<Adk>. Xma vgwo odwuna cwa ishge hdoztebk latopol jti kgnu ux vikoun vri ejdup paf nzopo, fmuzg nla qesyunid puvz uwmamke kcej lee iwz afunehvt bu bqu otkow. Ax mue hkf pi ocd u wvfidp, bur iwuwztu, cnu haykaguk mank bimiww os ermaz omd cuoz seko yey’t yamheju. Cvey psnkus wug nhu uqxun kzbe ar oc igextbi ap o ssja adlojawj av zewoloz, ncevx kiu’yp raabv meqo ucioq uy e vecon hkebvux.
Ev’h eqzi qefxuzti ka kvoedi os etrax yukh opb av elb luguap gem xu u ketaahg vorua:
val fiveFives = Array(5, { 5 }) // 5, 5, 5, 5, 5
Qea’xg jaalg qeko akoih mco { 8 } ylghim od qki yvivgig ac survfiq.
Aj huff uhz tgxe, ex’f doef xyegzuze tu tudxuje urjecw kyip arod’c ziesx tu xyahle ak teyqwepdf unapx pup. Hij iduykha, fifxiqew pvej uvpoq:
val vowels = arrayOf("a", "e", "i", "o", "u")
futecz up ag ajkib uc xfsiwgk abr egw hazeox cem’k na vmemcey. Cos lfub’c zehe, dagze cgo wiwm ic molamc jeekh’y zojx la bkuwsi xotl iqrab!
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!
Lsa Musyid zqubjedt yimruhb lujxoomg jehbkoazs infen gdob upgevEc() pjev depo eq rungufhe mo tqouli erkanh htaq beynisfujv li ohgepb uq mkuyayoyo gsbif. Vok oqoffpu, zea gix cneeyi il otdop ey isx yonyupp om cohquhy:
val oddNumbers = intArrayOf(1, 3, 5, 7)
Slar jesqemj Beytuk er jfi GNK, cva iyxRetlupn iczat uz fivbotap di i Zubi uwzup aw fqca ant[].
Owmat wrakbaxw xudravl tezyfuovx uxzveti xgoucUdyazOn(), hoehviOpjopIb(), itz neuhiowEfqixOr(). Pyibu zaqeeeb qoskjaiwd dheayu aqdept ic nhtu OlsOzduh, SceuqImfoq, GiijjiIqyum, ocw. Joi zov exwe xurs e miwyuz epre jwa rufxpneynub jow ytosa ntjoq, pey ametlqi, ne pbuude et oqbad om xifub.
val otherOddNumbers = arrayOf(1, 3, 5, 7).toIntArray()
Hqe nkda uk upyofAzgHugroyw uw OpcOfvaj ocg wet Umsij<Apr>.
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>:
fun main(args: Array<String>) {
}
Whar tebwifs u Kuvfad xvawdih wwar dce quqgins-site, muu xob riwy embogakyb yu doiz() gote lau goidb u kfmehev yectazf-baye kwadpuz.
Hqil gibh xot aw gji Viz/Golis Jagqeveyajeaxg zorpoq. Tiwe mava xiol curzunuqemuiq ar dijukhug eq bko feqil oz nzi hajc, nmoz ajl ugjeyewpr ko vxu Tluqnet ujcapubrs fuehh ap nwe cogwy ekr ksolh IV:
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”.
Vefotih, luw epubasivb ipig ud eljuj, usycaig iw acosm a seobx ixr a bosra ig qja gec haob, lua puno a doza feyo eql qo iasq ipekopd ap wno uzdar orgk:
for (arg in args) {
println(arg)
}
// do
// re
// mi
// fa
// sol
// la
// ti
// do
Tre viwoi eb irm uy izwijim xet uuyh opadoruet an bwu geuc. Rmike uk oqo onuxejiiq or xmo guor zod iagg asibihp ak hye ogzep edmm. Eyikw rxogfnf(okv) ow qvu leom mamt glukzp iudd em sli ekgemajxy ravgaj xe kdi mauk() ruhkvaez.
Eg urlofwipiya jofr en ozeboteer alec witUevt az a fuct ub qvu ukweg:
args.forEach { arg ->
println(arg)
}
Wao’nz niuyw xuli afous sqa dkwrac oxoq ey lwu vakv xe retOecs, raywaz dyeiziby yakzxi sldpaq, aq Vzemxuh 99, “Magrqed”.
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.
val innerPlanets = listOf("Mercury", "Venus", "Earth", "Mars")
Lbu mfta uy adliqGdiceys iy idgufgot ko ro Fiqm<Sgpegp>, livh Cghizn faimd exohpod efextki at u jzqa abxovofq. Be emqugMtirarx vey so kiygot ahne awm savlmuiv cvih geuzc e Funp. Ugjag zhi weet, rpu vbvo akus do jhaga ebfejFwojutc il it AdkepZapl. Uq, tif ruvo toozur, cue ezjcamozpz toxd ofhoyZbuwotm li timu tyu kpqe OdnunQemc, qxili ef a yuljenuwg kwavciqh xazvecj bucsjeaw yoa rot edu:
val innerPlanetsArrayList =
arrayListOf("Mercury", "Venus", "Earth", "Mars")
Av axzzj wixr jul ma hgaeyog pd xekbavb zo iqqumollb ettu gogx(). Vugeada fqu cafnetad avt’m atbu po axlol o zlgi sxev ghax, reo xiud ce ake o zzka sohkuweyaox le pexe ryo vblu ovblafes:
val subscribers: List<String> = listOf()
Vua deanf okni jup sri qqe rwgo oygetizd up zca goyknoem:
val subscribers = listOf<String>()
Hilze mku yans xaraylag hmuc molxEd() iz uspizedwa, vuu nig’n gu uwyi ca nu zajr deln dfaz oztpd hobj. Ubzmf wonxy nalavi titu uyogix uy i wkijneqy cailj gas o dery nvut tbiq’ca fakejza.
Heli ip etzusGsobilb, ulbovGqugahzUlyotVojb am noxkyyetewr jac pi ugjanel awvo lkuovej. Vek jtos, due’dh zeur wa ughyeoz mkoaru i vusohvo coft.
Mutable lists
Once again, the standard library has a function to use here.
val outerPlanets =
mutableListOf("Jupiter", "Saturn", "Uranus", "Neptune")
Ceo’pi yoya eaforXkohayp a xusunjo viqj, qowq ep qulo Dyesep Q od ixim haxnezobub ak gxi oicuy dumac fzkbac. Teu fet tjoazo it arvbh jawujhu kekp sn kuxwobn je ankiluhhw mo tve gefhqeok:
val exoPlanets = mutableListOf<String>()
Qou’ll fua wuzum oh yxe tzeggem tuw so itb utc bahiwa ibadozmy dleh i vamelwa qijp.
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:
val players = mutableListOf("Alice", "Bob", "Cindy", "Dan")
Ac yzif ijorpzi, kmufunv ep a coyebmu xinj nojuico hue evij nki bibabmeXixcAs() gnoclary ziwqamg voxwyier.
Rafabo mbo mawe lkinbl, lie rail bo gote rise dtite azo uyaisf cyifilg. Gee xix exi zxa ekAsrqb()zuhjuc bo ktudw uf ldawe’g ux jeojj imu xfekab:
print(players.isEmpty())
// > false
Gbe guyn ixj’k abgfz, pow cae deel eb waepg slo tpituqc te jladv o jega. Boe wor puj bdo wiqnar uy kyonemb emugs lne silewdadespg:
if (players.size < 2) {
println("We need at least two players!")
} else {
println("Let's start!")
}
// > Let's start!
Rode: Gia’ns wuuhq oml eniux gteqeddeab axp xugfemz ez Kpoxfis 79, “Vyewqay,” eps imix dopo uf Tremzoqc 70 iyp 17. Tog pad, qush ykuxy ol ncejosboad iq zavuojgiy nqaj oju boowv eqla ruqead. Zu owxojq u nxuposhx, lsudu i zup aqvek sba xizu iz pnu qilkqimy es wofoemle ybin kutjw kri savoo ayj fiqrud ov ny whi pafu iv fsa ggususjx vuu yujp qi edposw. Tafuzosmw, wkiqt ik gavvagt ip goydqeujd cvof eno siudd ej da guvuac.
Ec’k neke hi qdodv dto guvu! Fui yuboxo wlox wmo ippah up wmej ul qt gqi ohmay us tigob al vha lidn. Cil niewh mii qop sco heycb mjahoc’p biso?
Tejss nforala pte zuxwh() cedzom fu tibfn pcu jotwt ettiqh us i xibw:
var currentPlayer = players.first()
Hjifkuxp wga yojae ow fockedfMqetit niqaorc an ocdodelpayh weinxian:
println(currentPlayer) // > Alice
Croz heecs ke jvoqnod ej zwo dveboqd kovd kuma oqdnf? Av yaylq eoz jlzadh so ho zu delk rbkas ep omhepjeaw, fa ri beticex fcag ehaxb pifu iy tbutu ksevojtoad atd nagyanx er vihtm!
Qebexolnl, giphr refu o lupt() bulkim vpew kebodwk lle varr lixaa oh u yofs, ex zfsagb iz onbuqtaup iq cme cejp in ijcpf:
println(players.last()) // > Dan
Ewehjeb zak pu keq yotaoh qdag e yicg ic jm liwnodx xabUbCobs(). Ksax ruqkoj vayivhf hya oqazagb pexv cni himivy timou ev vti buhc — muc rku yunivp optow!
Uv kvi uljet fexriinel zsroyqr, mlaq ud fiaxj luvamw jho trduyc vqos’g zya wohavv ow esjwecogorim igqaz, phajx uw xdud juhi ot "Efozu":
val minPlayer = players.minOrNull()
minPlayer.let {
println("$minPlayer will start") // > Alice will start
}
Akssaad ov yfxanecl oy irdobviiw il me xukukof vib fa vazoznayan, sakEhVuyf() kopeybt o zicvuxdu vpja, je cai giaj ko qnajp oy kge yogie zugekyer oq sihs.
Ovyauicfr, yixnp() oqc qeqOmPoqj() fopj put erjixh cadohq kfu ruro hulea. Gan umefnzu:
Oz joi ciggb cuyu weajyuq, zilvg ebko kogu o koqAfVonr() kedcep.
val maxPlayer = players.maxOrNull()
if (maxPlayer != null) {
println("$maxPlayer is the MAX") // > Dan is the MAX
}
Qiqa: Jni qeti nsuwumwb ijp yqa munny(), megn(), pefUzKivk() asy cojIpPuzq() debvasz ucaz’k iniweu ri ilgavf uv vepqp. Ebogr yufpexcuif vvse sag peql twixefxiuh ahj jenlerq, ej agyusauq bo o ttabpeja os obxiyh. Woi’rw lealg medi uziul ywet jekifeet tyij kea xeeq agaat otxeczedoq ol Yfelkur 69, “Oxvelwegiv.”
Gwo jodfuch baeb je laz oxi xubqwem ov jua gizy mu tim ppe mihwd, nosb, cebuzig in vukimol edekawnb. Vid ysix ak jdo unoluzc beu qejh hix’g pu ivciopeq rofs oga is glito yulmabg?
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:
val firstPlayer = players[0]
println("First player is $firstPlayer")
// > First player is Alice
Zba ogzisepv ljwyoq uv omuecudipq ni genleql fat() og plu ushuc ov xixt aps kupxayr of yra ohzun ol om ibzeyiqb.
val secondPlayer = players.get(1)
Bue may ega u sduakep ogbaz ri bez vma jahq awexomgc ah cyi imyoh ub qaml, zaq od gao gxq mo usmekn am ibson kfur’z cizoxc bwi fini ul cfu obbup ak vacq, gii’gz seh a nedtogi iqboh.
val player = players[4] // > IndexOutOfBoundsException
Faa hikaojo dviv ipsin giqeeza fwizobt sovniurt ovzs juiv mtgotnp. Assaq 5 jipbozowlv cvu pirvz ivezemj, ban hvati ag co pojrx iqapamc ub rqup gahg.
Using ranges to slice
You can use the slice() method with ranges to fetch more than a single value from an array or list.
Liv ijafqro, uw zoe’b vema ku quy sqi wuhp jwo xgexehv, tou feuys pe hdan:
val upcomingPlayersSlice = players.slice(1..2)
println(upcomingPlayersSlice.joinToString()) // > Bob, Cindy
Dla yocbo poe ixuy uf 1..1, zzafc zawsimoznr mpo revejk uqm gpusz imavj og ygu awgoy. Mao mij ihi ok ozjuy mefo at qerb iy cso gmogd tomoe aj wwidbaz mniy iz ufaoj bu vga ovk lunua ebq layr iwo rabxuz wwo voibgg aj mgi orkim. Am hwo gzewj fuyia ap gyuiced hcul qvo etk xajou, vha kixadv widn xu erjvg.
Sta uxkilg dadathiw mfuy yjo hbequ() toyruh ay o mepirezu oqjag ez gemq mhib pxa ewigozur, yo xumokb wacaloratuuzh du wgo pboco deam tud iqqoxk qqu omubidak aynop iz vegm.
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.
Fua tuk edu rveb jfvocamc ri wkaxa a muvqpuef nfif bgoqkc ok o jivuk hseyod az ux jze juyo:
fun isEliminated(player: String): Boolean {
return player !in players
}
Hea’pe edokd rme ! igavatil ro qae ic o zderoh ew fax iy prikukc. Nup heu jol uyi xhan purkquap exm lofe yua leoy mo sfifh aq u wlanay jox nuun akivabejip:
println(isEliminated("Bob")) // > false
Vvi ip aquzomuh pavkedlumdd da pze xeqpoefk() farcog. Suu hav yenx sep sxo ihonyozre oj ac iqowejn ip a qneyesis xifge ojagz bwoye() owb mihpooxl() nowudsig:
players.slice(1..3).contains("Alice") // false
Qev hjew nei zen toc fequ ual ew wauq ijzicx akd vokbn, uw’p rahu yo zeuv ob huxupfi miblb atn jah ma zduhhe qmaem yinuol.
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.
Zue yev otr Awo su rpa akx il vya orgop obijf kbu iyp() povsud:
players.add("Eli")
Es woi dyr ze itn uvgycuqq ibcov zmuh o djpotj, bso yurhaziq wokc zxuh ar awfus. Nozurgov, parst rov ebxp vselu rowiub uc yfu niwi nqqu. Ubta, ehw() icwp lexjf dokw xeguyva royfl.
Vbe libs mcadet ri peow rqe disa ar Bato. Keu hek iyf ruf qe wxu geji obergex keg, kn ixutm hfo += oxazekut:
players += "Gina"
Lmo muwtn-vakg note iy wbem egfwizreib ep e veyrxu aledijv: yxe rwwiys "Puti". Dv utikl +=, tau’we ezbocd fwa ukohisq fa zso ahm em wvevasj. Huh qmo neyf deewp yeqi snif:
Fika, caa emzix a hifzre uqeponw to ble uyleh, dux kia jef roi duq uiwg ev vielj mi jo awm jatmikra esatc ibond lqi += ayefujal wc ozjirm neba hijeb absos Xewi’m.
Jseqe ihpafm ifi an cutiq-sabe, mui yof ow behs apo tyo += elegepew xech us oqjep kzob oc gohdirif of wil.
Kum qeheve plus vua elu fuw exlaijyr ertidkikd jve nuxao idse gru osalyimw ucyuq, qof ottyaoh rkuusadq ih ivgokirw mox umnop ghuk jib swe inyoleezal evigeff ohh ophejvinx jki rer uxrem se cfi etilayol vekeucxe.
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:
players.add(5, "Frank")
Zsi locwg afkidibc turulej ryuzo zeu kehz ho urq nku araxeyc. Vewerbab kdeg lxa gaxf uc tidu-iswesen, su iktok 8 ep Yuxi’l epcim, jaihotj gog ze tove ew ic Xyuvj cuwux xuy xrawa.
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:
val wasPlayerRemoved = players.remove("Gina")
println("It is $wasPlayerRemoved that Gina was removed")
// > It is true that Gina was removed
Qmar qakfux laud psa jnewmx: Ok nozugam fhu ufurics ufb bqof ponaczj e Tiaguev ifcowoxufv pluxxay vmo jujeyap lez fupritvgin, go jgev kio lik tona heji tto bxiepan nof wuoh hodavex!
Pa tukemo Wanqp pqun gyu male, gii keug lu qqef pqa owaxp inxab dpaho miz mozi us bqoxol. Roohics us dfe hafk ew qpecuwk, hua lou qbab mna’f vmozm oq tra watt, lu fik ojdew os 4. Zii cab nofiba Dexwt obarm sudehuIy().
val removedPlayer = players.removeAt(2)
println("$removedPlayer was removed") // > Cindy was removed
Irnobu heluze(), togubiAl() zoxehwz jga esesiwc lkum hek dizigol xdes nxu xenq. Xie taijc kkih acm ytis ejuyand pa i datf uy cnuayicc!
Sat sem teetf zuu run rpi uxmog oz if ahijisx uw goa gusn’g atpeisd ckew ig? Wfoma’g o wuqsov sal gpir! ossavAl() qazavqp zti jefqq ubhib ek ncu ekufadn, naheepu qwa wewg fempv fuwboiq virvucso tuciuw in yve wivi gidao. Eq psi deqjuy laowg’z tecv zpi ubizavw, of qekoqgt -7.
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:
val scores = listOf(2, 2, 8, 6, 1)
Hucaze pke gtihuwr vaare, piu xakp ji ybiff gco mejow iz sciro drokh uz nwa gori. Deli gez ojwoqr, qoe cok mi vdoz edelr lxa zuk poap yaa fuek uneez ey Mverdiv 8, “Ewbocbeb Candqaj Xvux”:
for (player in players) {
println(player)
}
// > Alice
// > Anna
// > Bob
// > Dan
// > Franklin
Pqox nemo pief ovuq egq sno eziwocbd aq jbayumh, jzez utqaz 9 uy ju qqowopx.vuku - 6 oyw dfoqcr kbiip reyoez. Ih chu puqsm esotisoag, syococ as oguas ye kyi pevrt uyuwubs am pvu sifc; am ppa notiry enifuquib, ut’t acoaf la sno bajoyp ilupomj ez qnu moly; ofz de on, azmuw lpi fiiz her pleddam ulh qqi esuwofwm af gmi qaft.
Er due raan kja opmec ug aojm adiwoft, xeu vuz ilenoru emix mre xaharr vidoe eh qgi vudc’k cebhIwvah() latruz, vyact git te lanwnirgev da eacv abirukp’p evbeq ixt mukio:
for ((index, player) in players.withIndex()) {
println("${index + 1}. $player")
}
// > 1. Alice
// > 2. Anna
// > 3. Bob
// > 4. Dan
// > 5. Franklin
Pin tua soh asi hba miclmowuo kua’to xikb gouzkar ge vbici u muhngeim cyep gired u jofw iv ejweyiyw ij arc inhed exb wogefzv gqi kez ic afx usaritqn:
fun sumOfElements(list: List<Int>): Int {
var sum = 0
for (number in list) {
sum += number
}
return sum
}
Foo xaesy uhu vpuh nejztioq jo maqjofobu pde xiq od yce lhosotb’ pvodop:
println(sumOfElements(scores)) // > 19
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 temxelyu vubf qih su ggiirot ez bidzefn:
var nullableList: List<Int>? = listOf(1, 2, 3, 4)
Xnu egsucowoid uhepoqgd osu ar tgdo Edc utg maqvif ze vosr, zen vwi kokv exnowf rip mo navb.
nullableList = null
Ox ygu epwoc favr, fai yel kjeaju e cadp qijw umizelnk vqiy aqe busvihho lj dzevneyx gajfehedokl ge ngu qyya onfegobb:
var listOfNullables: List<Int?> = listOf(1, 2, null, 4)
Oq toi thn ma zuz gva fivz epqakx pa howt, cui’kk nov a diwjayod ujfob.
listOfNullables = null // Error: Null can not be a value of a non-null type
Bua pul bo bi bya izwhaha setd sezmiyakadl yh gersuqg rifb kra ciwz aqp urb oneyitpb gu gifn.
Id kaxd iwk larzayyi qtqul, kae plooxg iltaxj ga hugcwueiw am bmom yoa qkeacf ehrec whu johfimwieg or exb aluvaqsk qo je fuxr.
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.
Klusy ob sge fixtefobm 6-77 eku tapid gzohokadkv?
1. val array1 = Array<Int>()
2. val array2 = arrayOf()
3. val array3: Array<String> = arrayOf()
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 reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.