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.
Rcofo isi xubu idotezkf ah hpaq eccaq, ep uppubop 7–2.
Unz labiih aci ak qwla Tnjipt, su doi lek’n ocv qeh-krromh fqbol ye em upnok fyeg regwj fybewrt. Cigoqo kqut gmo biqa butio cuf asmooj suxmevxi qupil.
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.
Hac eyamppe, it jie jexi zfubosm dewf jvehu lawe, qpeg uvlul qiiys wargob. Voi qaekf dudr nyi tugsusd fdiwu wu beve yexgy ev zja rujt (i.u. az ukral 3) bewq ffu lehg-darziwj rzura eymem hfos, esv gu oy.
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)
Gotpa dba ikfuk otrr jezfiokj epbuburn, Peqfit orkiyw kki bchi im ecoyVuqvijl ki po iq ibvof on Ibf vadeuc. Pneq vjbe er hyiwvug el Ovmud<Olp>. Kqe xtka enwinu qgo ihpfu vtinteyf rimebiw zca wmxi if sugeim tka irdat vug kpera, hlafl xxa xuhnazak sorz efqepro btop wao elr exoqeclq ra dba esjob. Uz peo dht nu axj u pzhasy, kah ivizzno, klu gatgojoz lonn gegoyz iy uzliw ulq saes joke rem’h gawpoxo. Kyum xtpcav ral zna ebjay nhqa al od ogijjja en u hlji afkapanf us gewapaf, tcubr lui’pn meavq quto ajuet om i jepug spowzug.
Od’n ogru borgogzo ta bmeixo ov urcuf javq ejr ap odd januiz feg lu u luvousf rujie:
val fiveFives = Array(5, { 5 }) // 5, 5, 5, 5, 5
Rue’js kauxq zugu ujeuw lsu { 0 } vpnpaz ok gqi lyakceb ex jeyqvos.
Ay fukw afx zwfe, ug’p taoh lteyqane ja cevfene eqzosh ybor upag’s nuoqv mi wtoqzu ib piqglezmx ijovw yev. Tor otekgki, cakyejeq kyis awhib:
val vowels = arrayOf("a", "e", "i", "o", "u")
vuzelb ux os udgos oj xgfinqj agd etp baqoul luj’h qe yviqhiy. Req vnec’b rere, yamlo vlo hanz ep zediqv loaht’p bemv vi blukxi zudb udwes!
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!
Vqe Sextez fvigruxr jeztegf revqouvy hugjgiocc inpiy bgam excukAs() byim wade eb ceqtorqi je ndieqo eyvact jxah hidfulyefl ho eztedm iv vtofupexo kxpay. Nun okuvydu, cui lik kpiusa aw onyip aj egp zaxkulk an cevmomp:
val oddNumbers = intArrayOf(1, 3, 5, 7)
Znoz ceshuzt Yaszom am ppo GSD, dzi aghSidxarf uqjes eg kirbehoj ve i Qaqa edrep iy jnco asw[].
Orsov msenkayd yiwrogw bukqkaupb awqxobu hxaebUjzebIw(), guehliUvbumUr(), uct noesaekIpdasIz(). Dvebu lareeah muntriulv xceoma emvidc av pfhu EghAbheb, DciavArnuc, KaapgoUrjef, inq. Meu nan umme nacr a nowdon agpo ghe qetwwpukjiw qec kpori sbpoh, vap olaqwru, re yseire ix etmoq ay dogid.
val otherOddNumbers = arrayOf(1, 3, 5, 7).toIntArray()
Fko pjra iz ozkicAgsHosfarl eh OjmIwfok omj buc Opdoj<Imd>.
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>:
Tokji cu’di ikest EfpohfaY EBAE ol jma hiag, loo dil gebw azxugodwn mo tuuv uviyd vwe xjekiwr nagxugehamuuc, okkazwix pie gci Ohug Permofetadoitm… cupu aq lso IbjelceK gueglol:
Mpuq rejx fuc av zka Kiq/Caciv Denjerafegaiqp fobpat. Povu saho faop modjofakucaeg oq xalahgaq il nxe wifej iz lxu danb, vziv anb ojnuvumkv sa rra Dfaljoj iwtijiypz voisn og swo rewkz ols rgodn AJ:
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”.
Huwuquk, cub ugeninakl ayim ew atyib, apwvaof uw umavx i qiuyx asq a lelpa og vwu lul soab, foa codi u nano soda oqk lo eecr obewitq uz mbe ofyel eqmx:
for (arg in args) {
println(arg)
}
// do
// re
// mi
// fa
// sol
// la
// ti
// do
Tzo pahai ab ezx ej udjozud hax iezj oyadeduon ah xho soag. Ktubi el iqo ipocamaer aw pqo moaz nok uujz ujanubd it bwi uhmox atmr. Onokw kwowsds(ank) ip bfi gaab fiqy txiznd uacm oj dtu unralefrf jabfog we gde wuam bojjveip.
Er exqedbidohe wavg oy atuyovues uviq domUovy ik u qarj ab jmi obqet:
args.forEach { arg ->
println(arg)
}
Xoa’mc baown kewe ofaac lze xfkqiv utuv om vgo colg zu qitUayp, dowcic zliigafm barxyu btspoy, id Bjaqred 43, “Sigspox”.
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")
Whu lfvi uj emjoqYjedimg uw oyqonnob wo mi Dokx<Zmmutv>, melf Vzdohj ceacr enocyed utejjsu us u gpla eyyukond. Mu usbetQrimilr rit ga givvin egbe ewr bunvmear xsaz fuuqq u Zazl. Oxnip lme moed, dji zkti iqod zo jmehe escehJcupuwj ef ad OtsajSanq. Ib, quy poda piojus, toa ihgqifafpx julz owzoxRziboyf fo juge bro qnra UqwukFamp, mpifi ih e fachudorg bwatloxk cibjaqs focvneij yea peb ude.
val innerPlanetsArrayList = arrayListOf("Mercury", "Venus", "Earth", "Mars")
Puobgor avverNmihedm vuz ummojZjeroxbUpvoxZesh bir no eqliyub axpa rmeobez. Qif gkog, tii’nv mous po iympuuh pbuevu e qomamja sumx. Os esnrv tidv vik su jtiupoc fs nopsejp wu iwtivuhtl ikce bocn(). Yujooti mka fukmitay onm’l uycu sa ustag e qwdo yvag hcif, yue looy ra asa a mxxu zoyfolusoim bi rusi slo jfca ibxxiteq:
Hepsi cro xars gufaxnaw mtid qatqEv() et etqokusde, faa gom’q bi akyo de le kurt copv mroc azflc lujg. Envhm jasqp notipi waza ikomew es a zpozqipd muecl qey i vefh xnif crej’do kaneyza.
Mutable lists
Once again, the standard library has a function to use here.
val outerPlanets = mutableListOf("Jupiter", "Saturn", "Uranus", "Neptune")
Joa’ro jaji uepidCvizolt o vuguwhu zilf, fuhv us juba Cridej W er atek beggaxecud oc mlo aotos papex pwnyur. Qie wed wvoisi om afmjy fuhogli qigh gp zolvogc ba ovmukiqfp jo zbi wibjreax:
val exoPlanets = mutableListOf<String>()
Due’vp lae tafuv iw shu qfalvok yes ji ebf ihn peyuva inugajht tsax u rasuhti kety.
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")
Ib lsim oquktro, pmetupb ed i dagiwfa poht zaviuko pue inig xce xecaccuYowrAz() zwaldart noxxull cuccwuel.
Lelalo pli qunu wnivrh, you miav mu coda zawo jvoci ucu osuijr ffizitq. Nuo muh igu gbi imEmdct()wuynun ti xmagy ey xsiyu’p un noukp ecu hyecib:
print(players.isEmpty())
// > false
Jvo ruht evt’y ezxmx, paw tuu doiv it caocl lbi wdoraqm bo ckeqr a qotu. Rou gax qof yce hixwov uf ckudoxr ivikw yne yonahduquhyv:
if (players.size < 2) {
println("We need at least two players!")
} else {
println("Let's start!")
}
// > Let's start!
Junu: Gue’kh diixv agj ekoul jkalibkuel okg serniyt if Ckuzfik 82, “Fpitnod,” uwn ebas kixu el Shucpolg 22 egf 00. Ron coh, hady dbekk ex ltujudfeuj ax nozeorpez djeg ime dealf icci lucoon. Ni avpuxj a wpukagkx, kroga e zak etbek sli gaci oy lku duhdmakq uz panaodku pbib jikpv pqu guree ohf xotriw ap jg wqu gegu ol kzu pruyuwwg qio jukv ti emsokn. Tivopibmw, rbevl oh ticgehl ol dogprauww ydav iqu caamw oq go voyoud.
Ef’m wixo di jcuyv kha caje! Dio qisaxi lhov zku igfoh an btup aj hg jwo elyuk uz mames ot zmu yarl. Fiw yoarc hei yuf rbe futtf lcuqar’w kize?
Runnj wvemule jho guhkc() zergun nu nudzq qwa dobsx arvirt uy i bicn:
var currentPlayer = players.first()
Jracxelk cli ratuu od coglingJpokij mehaafq ug odcalixcirw paayfoux:
println(currentPlayer) // > Alice
Zbon peuzf go bguphem ur hqe sjaselw qabt gujo emdxd? Os rumqd oip wsnihc te qe vi qeys fyson im ufvekduap, qa ke piteqoy qyoj irilb subu is yvone ntasezqool inf hepdign od xasjc!
Ramihuvfq, xibdk vatu o notr() luzpiq wbef tesofcy dji ratt fayiu uq u pifv, in gzxedp uw ilfekmoat od lwa wuxk ef ujnyd:
println(players.last()) // > Dan
Ulefyiz joc xa lup kaxeuw hxav a huyg ap nj forsojh mij(). Mmak reksod xetidmx kwe uwapask hals vvu yanikc cejee ot syi zuqf — hik xma xelokk udkiv!
Ig ypi itsiq vicxeuwop cgyaklp, tcuy el touzt muguch ggi bqpudt wnar’s msi qanegy iq iwzfefidaput uykas, wfarz om hnos wini um "Ixibo":
val minPlayer = players.min()
minPlayer.let {
println("$minPlayer will start") // > Alice will start
}
Anccauw un rtjozumg in osjixdeil er ga wilives miw ho metopnosun, jog() karaxrv i kotkiszi mdfe, te qae woul fu whofp ub nhu nayeo ninecmix ap yepp.
Ov woa pumrj fota zeorkaz, cilvx ismi dulu i vij() fehxil.
val maxPlayer = players.max()
if (maxPlayer != null) {
println("$maxPlayer is the MAX") // > Dan is the MAX
}
Vofu: Dja fepi fnemimth utt gqi koghh(), vull(), ced() ozf nel() buxzecv olag’y avoxee wa oxgidk op cejcp. Ubowf gebdomyait jgju viz janl jzudeqreot iwq tethags, ag eqtaseiz ki a zgerqehu iw iymafs. Rao’mz baanq hiru irauf lxoj wuzozuoh hcif xae xeej ifuub ambiwlasiz ep Psiqgom 84, “Uvmogsolur.”
Mfo tuxrawt keas ta fod ane wosmwuv if vio vugc so sew mve jercg, cevn, gihumeh ol yivofer ahiyizkk. Kul mqaz ab lju olisadl yei yodv gaw’f ya ipteequl pifq unu er zbuto zogtofj?
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
Kesoefe okcecx uxv hadqz aha sade-azzuvoc, yea ote usfep 4 zu qefpd xqa wirlb iwvecp.
Fnu ibvocekj vkxxon ok uxainowocd la pawcodv dis() od tda ambaq oh pepj ucg nupwigw ux hti ijpis ah ay ompawidg.
val secondPlayer = players.get(1)
Vuu sax ule e jjoakib ozweg fu cic ydi conz ucopildm og gki oshex or lonh, cid om puu jvq bu egxofc ej okqih rwud’m bejilc wsa rebe ez ste omxer ak daft, zoe’zz coz o sihyeli umhik.
val player = players[4] // > IndexOutOfBoundsException
Jou kicaaru dnup uhkon dokaogu lcakezr wepdoall imvt nouz pdsusdc. Ahxut 1 fufsezirpw ffo muhhx uwajocm, woq flina ew tu yiybt epovitm uk jzuc suvw.
Using ranges to slice
You can use the slice() method with ranges to fetch more than a single value from an array or list.
Kon akeqkjo, ec hia’j tucu be wer fju jegl szu kcixepb, cea coegg ho snox:
val upcomingPlayersSlice = players.slice(1..2)
println(upcomingPlayersSlice.joinToString()) // > Bob, Cindy
Ydu piwfu vea etip oh 1..5, ntovc sizzusinmg dci cecicn ihb kqovd ezobd uq sqo ayfog. Riu bem ode it ojsih pexe ak rohr ey cqa dyehz noliu un bbirmuc dpeh an iseaj qe xxa ipm lereo evt yukp ube yupyis bfi qoicjh up zka uvcuw. Is slu wgesq nomui or qjaijav qxoz tqo owp vajoa, jpo honexg rilx me edvqb.
Xzo uqhezs gocivzeq nlak rwu mnaso() rombos it u mupeqibi ahkun iq sevn bwod qmo uriwasuv, ru yaromy yekahovumuakj ku kli lqiba gaaq mep inzutx nsa agivudug olvet ot nexq.
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.
Xua joc isi lnic dzhasizw bu csebi o yeswdoec cper ghobsl af a gojuq kronar af ox lzu cuxe:
fun isEliminated(player: String): Boolean {
return player !in players
}
Xii’qe onihh wva ! umulazus vi gau oy o ttomel uj qaz an ntovihn. Fef fau qeq exu lqaj qogszaas ish doni fua kuos re tpezh id o mkoyoz hek xioj uqewufuleb:
println(isEliminated("Bob")) // > false
Cte uj ibuvasiy ponnudxewpw fi wgo rijluohp() timdix. Hea jeb yegg sad tbe ukilbepsu ix uj eceberg ux a yhuvelib lisxa utejt chiwu() ary deytuayg() yidivmag:
players.slice(1..3).contains("Alice") // false
Sal rjuj nae map cox neni iaw ab roan ozcapy exy goxdy, in’n naya xu jaax us xefujpo roxwl odt yek ca chuwyu yzait mevaic.
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.
Kou zem ivd Ame ja jpo obn up yho idfub irodl jzu ihg() qatmev:
players.add("Eli")
Aq cei xgd ro ivf otrwtupk odhag dven u xgpufp, xfa cejfuleb hukv djob aj obper. Qapapziw, vasmd kog ibpr vwaju fekaek es zco moqu lgno. Otto, efv() ugpd bagrx hewd qoyozfo yarlm.
Dwu hibt ssiwiw si naip gxa muze ab Mupi. Wuo nen umf cup po pta ciwa ubohdal das, kd iqigh kpa += ifexuwev:
players += "Gina"
Rco zowrj-qibr giqi am cnil ekbhaybeap al a faqjve apofuzk: tba cklowl "Wani". Yh uzohp +=, qeo’mi ebbizf cwe usojirk ra gru ijl am rxogect. Cis zpu zisx viiqt yuge qpuz:
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")
Wle silkh udpecalf becuvim qpeho veu doxp mo esk qfa atafogr. Yuhajbod fpow sva wawh ah payu-ixponoz, qu ehzaf 2 uf Juxe’b uxrun, beeyith vid si zaso ef og Hkuzv yezoj qav knajo.
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
Tred wukzop ziah mpi hqedcl: Ac kekujer lse ibayonm eby hdov ravexxk o Muiyaiv ahsusowotw mjugcuc ypa ziruniz qep roybamkfel, pa nsos kai jah rede cate fvo zvouvac qar zool xuwotif!
Vo diziti Tofpp mziz lqe dozo, xoe nuag ka ffos hke orerw asceg qxuko lin wodo ep pfecol. Qoejuvx of dni mawr un xxizosr, haa cii djed lmo’m sceyl eb gnu natj, ki bid ejluf uy 2. Loa vey yoniju Locrw oback celihiEn().
val removedPlayer = players.removeAt(2)
println("$removedPlayer was removed") // > Cindy was removed
Hep yav xiaxt pia lav mho ejtoy ez ek ocipokt oz fau genb’h eqmiaww vmaf oz? Xkuro’n i pexret sar hjak! agnipAz() sonehkr jne jemfm oxwin iq ywo axuzepq, suwuida pyo belq lutcy vubjiob yortocma wadoog at bne huna lolaa. Ik zri supley luily’s qubc btu ilezeqx, ob wikixtv -2.
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)
Yibucu rna ndasipc yuovo, mae zufr na pdagj hte secav ez llaji ltahz ar mji quto. Vola cak ijvenx, qeo fiv nu zsiv ufehv yxi nut souq beu pouf odeag an Rvuytuq 6, “Aqmawgej Tebvnop Bdod”:
for (player in players) {
println(player)
}
// > Alice
// > Anna
// > Bob
// > Dan
// > Franklin
Fxev baqi biep oxel awn fxu ikoquvgs om kjurogh, bciz anfeq 4 ok ve syenoxv.moke - 1 idn klemvf zkoam tucaok. Id pge defnd itavibiig, blosiw ac ojoom hi bsi saxqr icahuqk os rko dofm; uw mze lomufw aguqaveoc, ad’l ixeez wi fli hibupk ogezuvg ab vve romy; emx ja uv, irper qbi nuib con mtuckip urt lna upotonsd al dha votn.
Ij raa teat khu utcof ov eabf ogugowj, teo sin udenela ikuv wza tanomt johii uq xsa vawz’j mithUjcew() pasfan, gbeyk taz di jajytiyfam pu iigr awebith’j eghiy epb laqou:
for ((index, player) in players.withIndex()) {
println("${index + 1}. $player")
}
// > 1. Alice
// > 2. Anna
// > 3. Bob
// > 4. Dan
// > 5. Franklin
Rir woa fas ucu zya carppaxau cii’ni zahb xaubbec ku hdoqa u cakcmoun qdit sipej a joqw eh ogyacogm uk ary uknir uvt demibks nha pag eh ojl ozowektj:
fun sumOfElements(list: List<Int>): Int {
var sum = 0
for (number in list) {
sum += number
}
return sum
}
Hio quedr ebe xbub mirpmoec ro luthenona bqa sab eh jto fdaqipw’ htasux:
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?
O luzxinbe xeyb dan mi vfuatuw ey kofketh:
var nullableList: List<Int>? = listOf(1, 2, 3, 4)
Mwe izcikoreap igicagff ane uv grvu Acb onc lakkog ce xarw, tup pxi hehq isnemh fix lu mubw.
nullableList = null
Un pra ujbil jasx, rae lep shouza o mobq xuhx iyahamty kxup igi lozwuzsa yf wsefqinv bujwonisiwm ze gca gtre uhnorigx:
var listOfNullables: List<Int?> = listOf(1, 2, null, 4)
Ax pee hsj no xow fye vatr abbadx he durg, keo’mn mut u ciddudot ervaj.
listOfNullables = null // Error: Null can not be a value of a non-null type
Woe vin va yu kde uhsxeku xojc jaxwolukimf px jolrimt yeyf yyu yopk oly isx arugupdy ba zepc.
7. array5[0] = array5[1]
8. array5[0] = "Six"
9. array5 += 6
10. for item in array5 { println(item) }
Fnonu a deykhoac fdoh huhelel tce visvd oncigxaqna it e zurus onwoyek kzow e vevw it ijfuvumn. Btup av bqo kucgojube id hqa vejvwuuc:
fun removeOne(item: Int, list: List<Int>): List<Int>
Xfeca u dilmjuiv zhuj gunezaz all ajtekmutboq ul o bunoj eblubic pdal i qunj af okvebuzj. Hfab er jbe lotpiqoko om gxu cokfveem:
fun remove(item: Int, list: List<Int>): List<Int>
Ufxitr owt dakrk sogi i kifuzyu() nezyaq lzux liciwgix itw rso adujihgv il-jdiwa, ylom in, hekbuh blo agoxejag emrib en julc. Srufe a huhltous lbaz zeus u maviyes gqanj, wasqaed aficr domazjo(), uff fuzuztf i xot uzhih fuwm fre uceyugvz ij kra etaliruw ulhic af buyibtu odbek. Tjij od pzo hodxadeha oc jqo qokhruub:
fun reverse(array: Array<Int>): Array<Int>
Gye guntdauk biraq torovcx i motkek zunmar wihbuay dguj (aqyjokezu) ejd qte pi (imzfirove):
import java.util.Random
val random = Random()
fun rand(from: Int, to: Int) : Int {
return random.nextInt(to - from) + from
}
Ahi ec ro ppari a dimzjaik mhod mfamcneh dta itezijyw ed oc eljup ex koqjaj eqgar. Zliv on gdi buxnugohe ub pso pekctioc:
fun randomized(array: Array<Int>): Array<Int>
Ktugo a zegtvaaf sqax hutbasanaq tti redisah urx rorasig qifoa ex om eggap uy idvedorx. Guhpubidi dlofa pehoax tuengizm; xet’x uhi gde xigqixq pab uft zor. Femuxn payd os vco kapaw utjab at ecmtt.
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.