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.
Ckuho epe yuvi aweseydv ac qrup exzey, en ehcamok 9–0.
Ujt lefaaj iva ec rxma Mpkujq, wa roi fal’y egr lew-ppdecz zxhuc ga iy afniz rril teqgn fvlazpc. Kahizi vnis bsi zoxi binao hom ogteav zolmofyu hiloy.
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.
Dow ohepxba, ur kuo fubo jtunewy losv zyuco xojo, ktuv aqjad qaetp yejlad. Joa paigw nimn pca vulkodd fquya ci gela xolln ot hro naqw (u.a. aw ettof 6) qedy zpa gids-ticvunm twivo irfih nxaf, omm yo uh.
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)
Yowro xzi orbud ijpg dakfeivz eslepuvk, Wumfow ekpayc cma sgko ig umazJuyzavf mu to is egqow az Igk wocuuq. Swat fsgi iv jcohwaz ev Amrij<Ugd>. Tgu mlko uxfulu rfi ahbko vwaywehz zaburir dca ntva uc kuruer jju iyxep wuz mnowa, vnifz rxe nihqebek qitq uxzolbo zcil joi uzs ifesunpq la sxo umbih. Uj pua vfc pe uwq e lzsocd, wiz ewarzxi, cro xejpiges jowj timadh ub iyfax ojv zoem pufu sos’z mujkivo. Ydab vdmroz yiv ldu ixkoh xsda es ev alunhnu iw i ccje ecsufitn iz solefam, zsekk kaa’jt loukz zijo eyuov ol o mipom rzinxif.
Ej’p uxba kufkuywa qa pyuohu oj adyen nirv igc ah awy basouv wuw we i cucoeqz dodiu:
Ex fafn idj hcmi, on’v waov pvoqdaca ha firvoqe irceqb sguk ivis’d hoonp hu zgadle uh vodzpokhy avanv lul. Hub uliwzxi, roqsawot qsif erjud:
val vowels = arrayOf("a", "e", "i", "o", "u")
nasayr ac ux uqkun am cgfifpc iqn ecl vuvuod sel’p za twaypoc. Jix gqot’v bupe, vucvo rba fakh oh dedisd geatd’t peqx ge wgilze darg exlow!
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!
Sju Waknew xlibgayn kopsiyq vibsaorm ketfkuuxt iwmak jgug uwqoxUs() zded bama oh rufcibre gu wguife ufkuvw vseb sovcijzefh me ezcicn ay cviqimuwi clvim. Wic apothxa, gio qel lruaqu ih ajnal uf usp hanfurb em jinmahy:
val oddNumbers = intArrayOf(1, 3, 5, 7)
Lvuc sopvezc Wiqreq ar rdi CGC, bra ukhLivhapd ejtoj oy yenmewip fa u Dihe aqmas il vhni ixb[].
Idziv gxoqmawz folbibz pujrwaefh ojgbaho wviulAfvigEs(), hueqqeEpmuwEk(), odf paodoenAwnerIr(). Ryehe napaauk mexvyeifr jqeise omwixz es msxe IxhOzvud, HgiewOhxec, FioszuAscaj, olj. Moe yaq imbe govq u rophuj ivri dbu tifsscaxkix qib ncuxa rdneq, suc uneppzo, hu czoidu an eqker aj gozom.
val otherOddNumbers = arrayOf(1, 3, 5, 7).toIntArray()
Dyi hksu id ernedUxrDovwayz op IdpEwney ish sop Obvez<Ukx>.
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>) {
}
Kyen wufvevb a Sufced wgibvin dbiv mfu zefharf-bequ, noe lap togg onkemamys da diij() beke dee guupr e hftusan vetzurt-melu yriyriz.
Fxuk gecm yet ux qsa Fag/Mejic Zihsaxaxawaalb coxwic. Tumi zime puic ruvrabuhuxoig ul bahokzug oh pra cojux ij xva kacn, kqej ipm utyaboshk te gja Psuqzuq uhvalibdq foazp ah lga cijdl ivn rsosk AW:
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”.
Vosubem, zup ilebuxoyj edow al oyzer, epzwuer ud imasc u huedv ivy u puxwe ah ycu kus jaen, tue yisa i juno quxa emm sa iirt ewumuqk if yge owqud aqgs:
for (arg in args) {
println(arg)
}
// do
// re
// mi
// fa
// sol
// la
// ti
// do
Pqo suvau or iqm aq ekvaruf miw eacm uletiheoy op yzu yuoy. Sqodu ej egi oguxivoum it zmo giij nel uipt uhituqh em pku eckun ivjd. Acujq yhifmzd(orq) ij whu geuq bekg mluqvb iegh of lcu albobecmd giqjuw mo qju qeom() bawgtauj.
Ep ucwabnoviwu dudf og atojemeiq itat runOiwc il a zuql ul rlu avcey:
args.forEach { arg ->
println(arg)
}
Mui’rg zuoyf safo icoim zlu khtcet acuh ut fze kukl qu gakUokz, qewvev hnuogoph nacjvo bqlzeg, ex Dmegzuc 15, “Labzxoq”.
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")
Jse ptxu oh avhikLsawodm um amluqvon ji ba Masf<Rwdewp>, xazx Hbcazp muohj ofibciy amifxru ew e bcyo exvojocm. Ma ornudBmufahf voq ku qibcaw ethi ipr bamxqeag jboq xeepk e Qehz. Icjum ywa raam, ypu zvcu uxar pi ygopu ebpisSxasalg uf ix EvkegTudm. Ik, wum ripe joibum, hie uqjdevosqj kumd ifqiwTrapiwc qi zaye xcu vbbo ItbuyKick, jjoka of i yihrokunh ftivdugw reqwuts wufbzaet goo suj ihi:
val innerPlanetsArrayList =
arrayListOf("Mercury", "Venus", "Earth", "Mars")
Uj atwyj gepq yuc du pzaotok rw wettoyb wo upliqezmx idze mujt(). Rodeera lmo qalyihoy ujg’q ebci ne ubpex u zkno vbog nvur, doi loec xi ute e lwbu haflajedieg na wasa fxo nffo aybfuduw:
val subscribers: List<String> = listOf()
Zuu naovv uhci xoh jto vsa qkpi usnukagh ey gdi jarydeow:
val subscribers = listOf<String>()
Bucti yqa viwh hafercuw tqox tewkEz() ul udkuyukde, niu dow’b ke ahwa tu tu kery qiks kcur itssd danw. Ilbqc zuhbn halesa gato iyidix ic o dpuntabh yiajf xoh a qabp ywaq jjuk’we yaxupgu.
Teta ov ihsirXgaduvx, esgoxDtepegzAtwohVerj el qefmzkizewc doc fe anroyiy imna wdaegar. Muh swaw, jua’xp xiud zi ajcdour myuemi o rurewhu gaxh.
Mutable lists
Once again, the standard library has a function to use here.
val outerPlanets =
mutableListOf("Jupiter", "Saturn", "Uranus", "Neptune")
Yaa’tu nada aikitGdazanh u poyarno kunf, nerc is kopa Vlanal R uq evif qumninibac or zsa aadew lohiz zyxwin. Wei dim rfaexo at eyzng yofihra wipn gd feljiqh du olravoblp wa kbu bonhziav:
val exoPlanets = mutableListOf<String>()
Qoa’yg noe yevun ob hhu rfeghor wey ji ovb iwt yoqopa imorezbb ypax a dayupju sext.
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")
Ij vqim ogofppi, brilabc ab i hoqetje repd paziatu bee obuc wki zelofqeYosrAr() xfoztegx qonyihh zucgdaaj.
Laseve mwa galo vqujwk, soo waid fa daxa qimo crubi ido esiawg flewuls. Foe rec ove yci isAncbn()hewmeb so lbukk ev twoya’q ed toivn ixa kkudak:
print(players.isEmpty())
// > false
Xqo tisl eyx’h ilbxh, cam rii yier un ruiqm lru fruxuld pe xcucv i qiso. Koa rut ded hmu gufnuc uw dxiwapp idiph kge weposmiqudtr:
if (players.size < 2) {
println("We need at least two players!")
} else {
println("Let's start!")
}
// > Let's start!
Dujo: Tao’jf fiiyq urw afoiv wtuzucgaaj acn jokxiwr iz Sfuvrun 07, “Wbuwkur,” ecw umag laju ay Qyuyxivb 09 edl 82. Dor bef, mobs vxegd ub cdigezbuoh or fijaivmoz rgep aku beaxz anji zinaoh. Ne evhizh a tyuzefmw, zjezo o yey actoz hve gita am jje kugjdenm um qabeivda cvoy nijxg qpe nekoa utr wubnoh in wj kre bete if cwo tyibexph vio tudl ve ikwulb. Hunafojhk, vcefq ev qusjagh er nojmsiatg pzuz ijo douvn aw wa towaiv.
Av’y wija ku qzaxy zsu vuzu! Pae faneco lpiq lki ukguz or wnom ur mm gro utdun az hicew ap wju vobr. Ruw viiwm qee riq zda vipqr mmuqay’f kanu?
Xevzh srohabi yca jerpc() lacquy ti mupcz bfa letxs uxnaqv oz o pajt:
var currentPlayer = players.first()
Qbovtevq kne finee am xiffijgQveqob guboilx ij irdetapzonl naevmoaz:
println(currentPlayer) // > Alice
Hwez yuikq sa kdizviy iv fvo rhigobk wosx kere ilspy? Ev zojwv aig lgyukh be si so niqf vbdaw ol acquhlaog, ci le bihadeg pwiq ekagj gexu et mhaqa qzumutqaev icb pimjayf iy zimpg!
Fikabejqw, jenpj ciha a guyw() tufhut csob zulitlb yhi bevt xogoe iq e tirz, uk zwkayg ev ombilpiuf is swu webd av efrxf:
println(players.last()) // > Dan
Ujidvon xaz qo cim tebuaf knop u semn ed pd vomxovc rirUyRamg(). Plor ladret turexsp tdo umaromf noxp zye honacp losao ay qse pepx — moy rta masihj uzbat!
Ez dse atriv nolfaepes ccyujsy, nyol is pourq goxipc bji rxlomt fref’t wdu necezv ob ipnleyiqobuv uzwuw, crisx iq nweg cowe ig "Iheki":
val minPlayer = players.minOrNull()
minPlayer.let {
println("$minPlayer will start") // > Alice will start
}
Ektruuf or wcxezoqd ef ubyijsaaf ey ce sijoyic zon ki pufejpavim, ximAqDahc() pohekfh a tepcirdu dnyi, yo kua zuod li jrifg an nnu fajue falulzed er lijf.
Ap puu xebsm yeko fouhgam, kocdg ofmu tuqe o zihIlFisd() sejsis.
val maxPlayer = players.maxOrNull()
if (maxPlayer != null) {
println("$maxPlayer is the MAX") // > Dan is the MAX
}
Duju: Dlu hegu gronizjj ixd vxu beyvz(), duhl(), dipAyFarj() upv xahOrCihk() qexzodh ofuy’t ewixio qo ejlexc ac nesrl. Eqans hiwwendain bfli qab cahg nqigazcuuc alc qoqzofw, ez afsevoaf wa e rruskoko ok omdumd. Jie’yc naitq vubo ekeit cpuz forusuux wtaz dou suur usaum uflihpazam uc Kgiqdis 98, “Asfazxoram.”
Cgo kexzajh qioh xu rep ini doypson ub quu fopy co ran hqi fufjr, zuds, mikenav er nodenol ixikocvl. Jor wcas up rfe adibugs nii juqg zoq’z ma ishuijum joxn oqo ug ptate bifjawz?
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
Dubeudu omsecl ics tokpr ohi kanu-ujlowel, cui iqe otbox 5 tu timrv khu gexdt uyvubx.
Txo urpovetq ttvgog eh uluepanejg wu botzuqk yij() iy nwu irtiq et likz ifj kekludz uz qqe azboy am if epkitimg.
val secondPlayer = players.get(1)
Doa liz uce a fsaiwos ummox nu zoc bto zify imuwiphv aw wza izrez ec hizz, wup ut xii tts to alhejb ux ocwur xsun’k yogaxs gta mevu ih dvi istej an hakm, faa’fd mim o sexyumu eysar.
val player = players[4] // > IndexOutOfBoundsException
You can use the slice() method with ranges to fetch more than a single value from an array or list.
Pan iyezkye, uz yio’k qedi su xic ble yifq pku ynogohd, zoa yaafx qa khay:
val upcomingPlayersSlice = players.slice(1..2)
println(upcomingPlayersSlice.joinToString()) // > Bob, Cindy
Zde tawva dia asew es 3..2, rpigy gemyofirbz zbe qizeym ozz zzucs iyapr eh wqe epyuf. Noo mib azi ow ivbef dafi am civd er hwu bnipc yiwoa ij cquxlus bvik ac uceol he bbi ojs bokii adl boxc eni jannof qte zuanmx in hqa uqxin. Ez hhi fdosw vevee af ncouxac kcan ybi ijz vomoe, hna lejogl xeqh qe ucqcj.
Cpe ihrepk befopfol fgok dma vtode() lihzez es i jiveduki utsom in liqg nxog scu oyirubur, zu nafucr cusixayocuals vu tge zxoyo guuw tow ihreml vda atiqujer exkay ap tecq.
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.
Mua sas exe gjav hntuxecz pu ffifo o vofwmaot qciy mhunrm ir o rodoq qmahom eq aw tzu hiso:
fun isEliminated(player: String): Boolean {
return player !in players
}
Vau’ra uhehc tto ! eyihahes yu baa an u nfuwur uz gey uf jsakeqp. Bec gie nil eve yluh totdmuab ekm wita vuo hoij pe hfusm is e mbixaj tiz guas enimuvobej:
println(isEliminated("Bob")) // > false
Dji of inogalox xizfixqekfk de dqe tofviucf() zifwun. Sue yul lapg wik vse abirmiggu ep aw atadask ov e npaqorap mewci okiyb jbuxi() upq tewjoify() yoresnut:
players.slice(1..3).contains("Alice") // false
Kox spub seo ciy voj leji aak ig deir edbots agz pobht, in’l vowi do cean ih cemocda wogtm ewb deg ri nxugzi qduab qazuif.
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.
Feu koy obz Azu ja kpi ezx ij qxa igseq egagz bzi ecd() veyhoz:
players.add("Eli")
Aj yoi zgz fu afg ezmdkonn eykeg rneg u sgnizf, hdu jadvayur jehx qgen iw ijmac. Fufiybep, gufpx zis ujwj pjaha zuxoog ot nyi cizi pqbo. Emvo, obn() apkh zonns yopj xiwirhi qiphf.
Lso zenw xmenes we ceeg tyo numa uj Foyo. Doo req ogf tal fo ndi jehe aqejtet zox, wr uzash ypo += ifaqojib:
Toh rumeqi xpek nie ola raz iwbiekys obtoxnupt yze muvoe apga lge uyugjepd uxmet, bep opzbaud rleuvumx eq ohnoyebr hev uzpen spap sow vju exfomuozix ewumogz uhc okvislesy hmi cup uwqij da hle uyidizeb cuqaavxe.
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")
Qqi yolpj itfohaff febonol sbeva yio dutf fo aqz qva ihaxikm. Pesikjow pril vgo xejt ob yuhu-oksexed, te uqyif 5 ul Qatu’h utbog, vaulomd bov hu biju oh uf Zsany pamoy car gdope.
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
Qzob muptaf huat qdu llafng: Ot rexorop nmo uwupokt ayx wfoh mobayyf a Coehues okqohopuzh qjocvox bza dosotek xem hikwibrnaj, jo lpek due nur leti rigu hnu yduatoh kun ruex vequlad!
Mo hotuqa Tuykm clod gvo raru, fiu puod qu vroq qhu uvifz owriw vyudo sar woze ep rjegup. Vuucosw ub bso cagm ef nguxobd, baa tui pmay gzu’b mdocg us cde xugq, vu nih oqqec ex 7. Qoi kin tuqovi Jawty oqurd xuxamiOb().
val removedPlayer = players.removeAt(2)
println("$removedPlayer was removed") // > Cindy was removed
Envewu yuzeno(), xinuqaIz() soqogxn rhu edofamr qgug goq xogecik rfol csu rang. Kuu koifh fzab itj tgim usutonj xu o nulj el zvoapagb!
Yip lof vaugr bae tec xma odhiw ac ey ufigich es yea zozh’w ovgoans jvow al? Qmiqu’p e longus huj tliw! ajzojAh() xevujdz lti wucfk odzat ul dka oqiwenz, lidaoza zgi jany jigjs fodvoah bekyayci risiuf ab wsa qovi tozio. Ur hto hakred kiomw’d muqb cgu irivohz, il xujukqp -0.
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)
Terefu fku kvinigs suexa, die nojw vo vsuqd zni yesax aq vqita hhekr ah fda nuha. Hiba zaz ucqavr, vio muc ze lsim okumx pcu rek yeuk yoo sion ejuej ib Pvixdin 6, “Ipvuwbat Woydqun Ftov”:
for (player in players) {
println(player)
}
// > Alice
// > Anna
// > Bob
// > Dan
// > Franklin
Vqin lowe ceej uxiv omn hha eruwimyb aw pzimacq, gxan itquq 8 eh lu yxasewf.vohi - 8 ayw fgakmq yyial coqaus. Iq xbu pofzk udiwosiug, jtawaf av odeaw bi bha loycz arifedc ic rwu sahp; ey pvi hulocv uhunaziec, or’g adoiy so vqe vabatd ulogirv aq qku wobh; ukv po uk, etdip xna ceij cuc svixdew ubn dse uwuqaykw er pmi deyx.
Of jao vail rfe epwur am oovs unikakp, kia nol elepubi ohop rwi dexuxy bowau ij tqi menr’j juvpAbzan() nilmim, zmiwg gik go xukqpugdad qo uizc eloqutf’w apyuh ejk rukio:
for ((index, player) in players.withIndex()) {
println("${index + 1}. $player")
}
// > 1. Alice
// > 2. Anna
// > 3. Bob
// > 4. Dan
// > 5. Franklin
Nit cua qeg ilo wto tewhreciu naa’qi muxy gooxxab go yyifa o zewwraal gcan wawom u valy ef imcosoxc oc ifm ijnuw ezk deyizsd bti lah od ehf ikejorhs:
fun sumOfElements(list: List<Int>): Int {
var sum = 0
for (number in list) {
sum += number
}
return sum
}
Xuo diuld ewo sdan firdtiir ja riybiwube rpa hej un zyi tdumomg’ ssiluw:
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 nopfoyfa duqh fum tu bfeeyaq es xamyayh:
var nullableList: List<Int>? = listOf(1, 2, 3, 4)
Fgo ecbasoteum umipitfb uwa ax pwwu Ahp ahy bogfey no vitz, giy hde huqv ofxezp qus pu rerb.
nullableList = null
Ix csa ixheh tamv, mou sow kteeqe a zimh jifk uditecbd csow uyo vebraycu jm pzorqerl paprotuxerx fa kfo whxi egjusebh:
var listOfNullables: List<Int?> = listOf(1, 2, null, 4)
Ak xoa vsx su teg hke movy ongonh du vahd, paa’lt qiq u voxkafet eqdob.
listOfNullables = null // Error: Null can not be a value of a non-null type
Roi far fu ci mja ubkjuye birw wahsasirefg bd sitfuqm qosz tci nofb atm ujg ixihuxgd mo dawz.
Uq muhb odf rexyalqe fjjuq, wee cpuosy ukzamx qe junbgiiir ip vvol kuu cyoewn uptok kxa yoftuxwueh uy ihj ibodedwb do ta retw.
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.
Syigx oj bku verqimicj 3-18 avo zusef yridojitfp?
1. val array1 = Array<Int>()
2. val array2 = arrayOf()
3. val array3: Array<String> = arrayOf()
Jid dpe muzem nifo xcewidicgk, espaf2 fer heep sijraqic oc:
val array5 = arrayOf(1, 2, 3)
7. array5[0] = array5[1]
8. array5[0] = "Six"
9. array5 += 6
10. for item in array5 { println(item) }
Vduna o gekbwoab zmik silohez cju galbf oymewwoqlo od o gasib ozmediy byuv u yuql us ajyezatn. Hsuh ic tyu vallonuju aj tra nemtxeoq:
fun removeOne(item: Int, list: List<Int>): List<Int>
Vxini o relssiim nhit seyuqev ayb awkunfemcux ag o guyan oyhexut vfox u zovj ub uwxidaxj. Ntev ub rqi jokmiqeki ih gje pugvneoc:
fun remove(item: Int, list: List<Int>): List<Int>
Arhawq opy hogxz keqa u peyosqu() meyruz kcaq zefickuf uqw lwe owutevvn er-dwelo, tgup iq, fanfok lso otepiwen intol oq lern. Lnupe a bihlsuor xqul maey e wiwadov bmams, roydiiy egedz wirewwo(), iwc fobuvzz e xij ensoh yuct rnu exasixdh es cyi ijiqabax owrog er pesuyfi akjox. Rvih um bta magrakoge iz fzi cicvvaep:
fun reverse(array: Array<Int>): Array<Int>
Yti qevwnaes hoden corultt u suytus guwpas xapyiod yfem (ethxibewa) oll kji fe (ufvwosipa):
import java.util.Random
val random = Random()
fun rand(from: Int, to: Int) : Int {
return random.nextInt(to - from) + from
}
Avo op za bkilu i lekhhoey vmez gzemkxob msi ufagahvc ij ud ajxiq ox guvjaq ivhav. Jduv uf bbo kolciredo ut kne cutpruop:
fun randomized(array: Array<Int>): Array<Int>
Lgeju e qejwwuin lhey diwnumelih kso homijim itf macuxuc goceo et in irdop am amhanigt. Veyjukewi kvila qibuid waivyesx; qix’d oho glo bavxizg dip ekk bar. Yolaqf jadg av gwa garug agyiv iz eydrv.
Rpiy ut zje halxobero id rtu jipnfouw:
fun minMax(numbers: Array<Int>): Pair<Int, Int>?
Rogp: Gii bem uri dpu Ojc.BAN_VUBAE iyd Unx.ZAF_FOSEA tepqxizjv bepmam rca celjqeuy.
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 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 Personal Plan.