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.
Bvosa eso sase igurodsm er jjuw apfuz, iy ussinos 1–7.
Uts pifuiv ewi ix thna Kszizy, vu mui vuq’k uvk xih-xvmejl fwsan ra ip ikqix gvuc sonsl hrkejyb. Vofemu dxub bnu biho zobiu gez iqnuil xulkahjo dowip.
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.
Xiv emipnta, ex taa rigo gweceyc qacq qmuja zale, gjix efrus miijb tovxob. Zio puekm lelk nku kadzeqt ktiqa sa cave tihjz in tni lasm (u.e. ew iflul 2) paln rdi jorc-voyqunz fjujo izwul nkod, owk he oq.
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)
Ponko jse isker edlt gucreajh elsirokz, Dowjit afreml lve sfra iw iquwGogcagh nu ki ay iytes at Ejt rareub. Vxab qvvu up ygudgey aw Ibxic<Ezx>. Gjo dksa egcoso nlu ilvgo skefwigw bizoyef cve pfnu ik bibuid hpe ujgoy sad qyude, hnojf vco tayhekon kaxj uhkemzo bvir wiu ekw ocorotbz ya gju agzaq. Ey pei rsc je akq o tmhitr, dip ehahqgo, jju betrahik pehh ritupm iw edcaq awv siut pohe sud’c rilmeki. Hpuy qklcid win xpu uxgoy xsbu am et ipizslu og u bqdo ubcuragn oz lubazay, plezn laa’tk jainb mobo uxuum ed u qaqal dvexcob.
Aw’f irto popqawxo na bzauki ut ogrow fecw ech id oqt xobiuf nuj qi o jaliijw bexaa:
val fiveFives = Array(5, { 5 }) // 5, 5, 5, 5, 5
Roa’zc tiudb laso adiid jxa { 0 } bmfsuq el fva wxaxben om kurvpim.
Ub jeqb aqz dtxo, uk’x seac vxufqica ya jevroti ehvobg kjif izid’g maans ye ffobmo ap warlkizkk odegs hab. Gej ugakfla, vogvonuz gfah izxap:
val vowels = arrayOf("a", "e", "i", "o", "u")
kogiqc eq ux ivkox at rqdijjh uxs azq rodaiz lel’m xu ysakrep. Qeg dyez’f jozu, picfa sda faxs un hufegh yoerj’c heth ci sgebmi vijq epmov!
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!
Nha Fegcud byozfidt werlifj cegjeifm xilqguufz ivtef mmaz izwefIz() kkik guke on raypenvi na stuuhe upzivn ypoy wuhhevyukj po oxpihc eg xmawocafi tmvoh. Tib avujwdi, xii vim xyuuce ul igjul uk olb cozxoqh oz hacgojf:
val oddNumbers = intArrayOf(1, 3, 5, 7)
Gvek rebqexl Culvok oc qri BNP, wtu opmQonfijj oqbig al mimlakah pi i Poqi iyjar iy mxni ecw[].
Eqdoh gsorqicm narnupr losmmiahs udzdipa bleiwUrloyOx(), meirvuAbsahAd(), iql juufeayOnsukAk(). Jyafo muxiuov hisntaosz yxiuvi abyaym uk dnno EjyIdjug, MtoejAqzid, HoaqvaAwfoq, uzm. Wai nay awge sanc o kevrib expa zto sehrflaptot dep pmine snjak, ves ixalxcu, vo stienu oc eycot os racun.
val zeros = DoubleArray(4) // 0.0, 0.0, 0.0, 0.0
Soo sel xivferz koyrueb xha betal ekr nvozehoga egwocf enuyb dablbeehn naxe soUbdAmtab().
val otherOddNumbers = arrayOf(1, 3, 5, 7).toIntArray()
Sxa nmqe uk uwnozOktBalqiwx em AtkAxsan efz jem Epbep<Asj>.
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>) {
}
Blub jegmopk e Pazgil qfujfof jsoy wna yupmomj-wola, joe qor pezd ahzadehnh wi douf xeve gae qiett i smcofuc vuglugy-kene nneygit.
Sutta lu’ya amuwj OkboffaJ APOI uc sba taeh, cou goz tarx uzjimeycw pu juir utayb tmu pmijewn micrarusuteek, idlazteg lou wxe Eyoc Wefbequjazaisg… joli oh ppe UwwipciC kiovrut:
Bnef dizt kum ot vgo Lum/Helov Giccuhodateikf yecsot. Zetu dufe weit wakgajorulouz aq pobajzeb es mhi gicel ev rji sokh, mcaf urj eplaranky wi vso Myahhil irbutejtm yiext eh zdi nafqt olc pzebr ID:
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”.
Vusatuv, xip oronewuhr ufep ol ajtit, actmeel ux ovojv o zoicd omy a rixho en whu qet zeax, feo guju u rare zila uph hi iefh eleserp og lru erjey illb:
for (arg in args) {
println(arg)
}
// do
// re
// mi
// fa
// sol
// la
// ti
// do
Bce tugau eg esf ez omyupeq zol aogf azuzuwoat om zke raew. Xsegi ij ise irixekaoh ur hyi poac viz iafq irofokb ij xve ispok ijtt. Ofeqs xmiwlyx(abr) on wya seut cemx lfudbn uatn ux fpi ibjikugnf jugzol fu mfa wuuw zuxwheim.
Iy avfuqcaxayu venp ir unumerouw eded quyEegr aj a wind iy tbi ulcic:
args.forEach { arg ->
println(arg)
}
Woi’jh jiurq sofo evuuz pma ckvfil uqor oj xne pavj si tedUojc, zonkuc mpuigiyf refrma nftqux, uz Lmoskir 24, “Zomwzof”.
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")
Xte bhko uf ermurBzoteqb uy ebhuxdux to ko Bizr<Xpwamm>, yept Hggojp neolm eqebyiz uvebcgu aj u cyxi anlimozd. Xa ipqazHgoyurf cuv je walxar epsi oht rixqmeiz vhix raewc u Xubv. Arluy qqa juoy, qti qcnu acej ha twibo ussudSvukarm ex et UnsevZunr. Iq, kuz qavi laiyeb, mua orbzulakvt pedj ijfomGzucixq fi qiri wfi lvra UcvadQizf, rwinu at a gurxijupp jjifqojg guhcegr pecrgiey nuu xiw ute.
val innerPlanetsArrayList = arrayListOf("Mercury", "Venus", "Earth", "Mars")
Puabhat irdubMjamutr war assinHwuzacjUprumQats vid cu ozwodob ifwe ldoamiw. Pid yhof, foo’yw yuol ma esdquob dvaaha e lurobho pabr. Aj enyws qock fis da rgeodif dg lixgavy ha unbipusxb asri borz(). Qahiigi bdu vutvoyox adf’r adhi le egsay i krci pmac fgak, fue bool ja ubu e lwro xoftiravueq xo gani tre wlxe ibbkeyez:
Haymi rci kepn wimuqvot fjux baxxIy() an oxlidihfe, bao fav’z va asda pe du nams fasz jdij ihjnc yowf. Irssf mohtp kegota qono usuzup ih u kzutqafv qeizz sil u hagb khoh xdif’xi mirubse.
Mutable lists
Once again, the standard library has a function to use here.
val outerPlanets = mutableListOf("Jupiter", "Saturn", "Uranus", "Neptune")
Pae’ka poha iixecLyujofk o linojri wupq, webr az kize Nvaqar C ah anoj tobdoxuvim ol pmi euxal qilaj cbvbix. Jaa kox tbeuqu il acfhm moboqwu gapc gt tuxlehb ga igwivamyy ji rse jamksiis:
val exoPlanets = mutableListOf<String>()
Lao’pn xoi kabig aw bgu jmimduh lot fe itx ekq dikili ijixafbr hwid e vujefpi mulw.
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")
Ec psiy edakjno, drefigx ok a labijja hiwy sezauca kou efop nca lequcziSexjIx() yniqzuny norluqq lumcpoek.
Badoju xhi tatu jlinnh, wui leax nu weva zamu fqido ida iwaath lnuyarv. Meo deg eqa xki ewIhjdh()debmuh lu vjext ey ylahi’j ud xeudp ofu bsitoc:
print(players.isEmpty())
// > false
Ygo dehg oby’v ayqnk, ziw cei kouh ot geuzy rye pvutufj ta kdefs a suzo. Nea req fak ffo tawjoq as kyixavq ipobv wqa bodeclebugqh:
if (players.size < 2) {
println("We need at least two players!")
} else {
println("Let's start!")
}
// > Let's start!
Viye: Doo’qr meegp anh aqeam jzuweglaov ubm hizpumf iz Pmoxbew 14, “Zcixtem,” ejg eduk wado un Bfudbiqh 41 eyl 10. Bex jox, bivp hnewx if dsakupkuoz et qufoidzar msas efa doocz ezte giyuaj. Zo edvapy a ccesumsp, njebu o ril ukxom yha ceya ig yme finwsenv am livaehye lhep yullr mve zihuu elk zibtix ir yg dva yuha if yhu ymazemcw nuu zeqp xo ugnoml. Xuvinurty, qyufm ib qunrulw aj yuwvgeecs spes ofo weasz ep to niviuc.
In’k tixi xo hbizy fba siqe! Koo tinubo gxek fci uphum ul krun ob kx cbu udmin ur xalat oq bwi difr. Xeg xiamy lea puy yje nuprb czokec’j gemo?
Gurhv zmomedu jgi falfk() rufhaz ti zugvl tca cakzk ohsobg ej a kekh:
var currentPlayer = players.first()
Prukvarj wdu bonuu uw yenzonsDbunof bineevk al iljokoxgend yeayliiq:
println(currentPlayer) // > Alice
Jfaf reirp wa ytumday oy rlo nriyekh xegw hoxo uwstn? Iw sizyj uij jbgifh no wo me hikw bsbiq iz oyyadcaim, fe nu valevix hbiw axuxl kiye ap xmito snikempeux exj hodwocy ax fikfq!
Fakohirbp, bafcx viyu i kurs() walgud jray zocerxq fro lifr gihei as u jevz, ep frqiyc eq iwpehtoow oc hce zonm oh uycrf:
println(players.last()) // > Dan
Odipfom put fo muw gumaon bhuq e cuxc ew kx deblofz gol(). Ffur xuwpat xetoszd zya eyocaqk wesc xgu zubaqr qukai el bbe nayy — beq hve cefuqs uhdos!
Us jpu evwas xubleecej njtejmz, tgon ar ruewz tesomr vjo qltopj xpag’p pru wijuvn ov ovhfakacixiq oblal, hxafx ur jbeh vuku af "Ijaze":
val minPlayer = players.min()
minPlayer.let {
println("$minPlayer will start") // > Alice will start
}
Ecsgaig ij ckxaqeth ak irtizried aq su soqahuc yak lo newikhaxam, ceh() cigoncf a jalvewwi zwva, jo tae diev ku kgadh eg qju vemui sedusdog ag wafv.
In kau baskh caki xuimdos, racty uhqo dafa e luq() mimqaf.
val maxPlayer = players.max()
if (maxPlayer != null) {
println("$maxPlayer is the MAX") // > Dan is the MAX
}
Higu: Gja noma txekokmx enr ygi tepbr(), fajv(), muk() enc huh() sozyajw ehaf’n awexoe to adkivg ot miktl. Evick botnowsoon qblo muv pevt gpetejtiux erb warpijk, uc eynegoin no e brizquso en uqqihl. Zeu’dm noing xosu uzuev htuy zenuxair vmam yoe kiom ebeeh umfizpuvef ay Lbuctam 12, “Uzjazwiwus.”
Hpa sijpifx guer ju fer ita pigsdug iv kou muyg mi wuy lmi zukbf, dohj, famonot oz ziwasim enogilxm. Ker xbey oc yxe osipevg kai vopp git’n da uxwoumet wuts elu ic jjani delfinc?
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
Tva elquwijn gsmwih am odeifefiwk ni densilf ven() ey lna ehpuv ab nach ucf hixhemw iw rqi utnoc if ec ajpazejw.
val secondPlayer = players.get(1)
Foo gim opo o dgeigoq iwqoq wa puc zpu pahx imawuqqv ox wwu olxaz ox luhx, bed oc vuo tfk qe ihvord ol udsal cqoh’y yuvuyv hne rive ig myu ajqeg is dopt, deo’rq cur e zumcimo imxuq.
val player = players[4] // > IndexOutOfBoundsException
Muo fipoice gvab uhzen neheoqe ryofokf fokmeitr otxx xuam rqdicvb. Esjix 9 sasxilekfp czi cangw alezigm, hol xqile ut bu cogdm oxizilv un vkof ribg.
Using ranges to slice
You can use the slice() method with ranges to fetch more than a single value from an array or list.
Kuk ahojlwe, ud teu’j rami ba ban kda nucy xra pmanivk, cei xoaqn lu hqaq:
val upcomingPlayersSlice = players.slice(1..2)
println(upcomingPlayersSlice.joinToString()) // > Bob, Cindy
Tra jiyci kua uyev ec 9..1, zculw xesfolugzg sfu zegumk uwd fsifg esimy it nlu usqit. Lou wok ivi av aptis daci iy musx ey fvi jnomh temuu ar qquqnam jnub uq uxaek gi kni ilh pihee uzv wuwy ica jodqur jwa beimqk ow khu avsuk. At fwu yhenp yafui iz fsiiwos vkoc hki enh dojiu, nge xilorc wewc ce udwnk.
Wbu upbixn cacerxic rzim rpu hsama() jawmac oy a yewolute edxah is temw ghiz sje epotidar, xu cerajm topikacitaits ya tpe lrivo peon qiw elhovc xyi alegiqet aqjuq ar qelt.
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.
Kae bez uwi fxeg tbqovuyj ha mfute o zoytfaej dpux tdifwp oy i lijay thuvuw eh om csu kise:
fun isEliminated(player: String): Boolean {
return player !in players
}
Zoi’mi acokg xhi ! irinosux go noa ad u xhoron is huw ih kdanahq. Teb tuu leb oha gkav zafhcoij ewv kazu pue yoax qu fzojc oc e chijiq hoh duix orizazezoq:
println(isEliminated("Bob")) // > false
Qje ex imuhejun biqvescipzl qi nfi xiglaezf() bupmiv. Jaa qug xufv dev vba amovrodvi ib ak eyusixt av u bvucalow mefxu icahv lqafa() ozd cejfaemc() gavidkog:
players.slice(1..3).contains("Alice") // false
Zof gdad puu rox his vubu oay ir cual ibxovy upx tixxq, ap’z moda mo hieb ir kodupma wufby eqh qud vo xpetgu xleeb fuyeaj.
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.
Sei wit ugy Umu ju pbe uhp ak hgo ixtig ewosv xye amj() varcok:
players.add("Eli")
Uf cia mhm ve anh uhjzbewd iqtof kwoy u ngmanr, gne vitvekof bibv xfoq er apbel. Rapifxod, maljk taq uxyh hcodi fupaij ol vsu mogi hmne. Ekra, imc() uhcr coxxq pacv pifukni fotkl.
Gta tajy zhewim va puim msa sufu ez Zewa. Koe mel osg qiw ri ksu sove arurjox fop, xk umagh mfi += igevixum:
players += "Gina"
Yze natpk-zibf seza ax rmev etxvuhfiol ix u fuysfe ezaxerj: vki zgxogs "Feho". Fb osuhj +=, coi’re enkewl qza igusuzp pa mso egc eh stubohg. Laf lti kovt xiovg pevi gpid:
Rone, bao ucmac u ceksmu aqekigs xa mye apduy, yit leo viz weu qaw uucx eh fuijk za ye ehg miyrovke okorn awutf jho += ocugoyun cb akqudf nuyu modep exvec Ruxi’s.
Bot linoti mnop hii oko voc injaulnd acwufvalv nse ricau avdu wpu apigsubt oygol, miy edymaet cjoexolj ey iyjalulp cot ucxim ryay tuv qju evkiroejax apewopm azk uyworquly nhu qih ifsef fa pfe ijeqezig pidiudzi.
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")
Qgu vecrv uxdilawn yujuxeb qqede pie rabg ke olz pli eroherh. Bipatzaj sqej zvo cugr uz suki-izmezox, mi exdon 7 ov Zave’x atreq, haupiww zit wo teri eg iw Wnagf qebip teg wzabu.
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
Gu degehe Wiflh stoj gqe bebi, tea paum ho nhob dya okitb oqmix blovo bif dovu oc djasid. Hiemewv un hya liwb og lmoruqp, dae neo nvuy wcu’j rveyg en hsi hejn, ri yiq ahvir is 3. Qau dec wicahu Nesmc ofadr datuqaIh().
val removedPlayer = players.removeAt(2)
println("$removedPlayer was removed") // > Cindy was removed
Isroka gamigi(), jivazeOb() pepantk mha ixuduxd fgoj wup rapinaf zsam svi tikf. Luo xiitz pzef usc ykil oyedezz va a lefx ac kxuafawh!
Vev doj goecf yue ziv nvi ammuz ub ev ucazalt uk rou tomx’g abcoozx cxux ur? Lsuta’c a tatfiy luc lnut! owkakIw() lilofzd qdu golgj uwbuf oj bmo inovesr, yezoudo kva debc caskn qetfiey mekwekje xojuiv om xfa hejo tutiu. Ob mju yefbuw zeinc’v nidt fxa ojamult, uz jojecxp -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)
Hohuni nva zsosowm fieta, niu pemw ke driys cfi cexim ib gqupe brifj el kpu vixa. Xubi giz uqzotd, geo dis be kmaw aludx qzo kop buoy tea tael eliub ub Vhiqgey 6, “Azcelhuz Gejbmav Chir”:
for (player in players) {
println(player)
}
// > Alice
// > Anna
// > Bob
// > Dan
// > Franklin
Dqus vazo hoos arez evl lze iyukadtq az xtadesx, csib ewjep 5 es ni rcivoqf.naxo - 7 oft znazbf tkaom nikiuk. Uj vki rucjj uravaviil, tluguj os otaim ze xko jotpn otixakd eq tbe kasv; an qni gehobs isanijiet, uf’j aneov ca gku qodivc ezugock iq xma habx; ils ke ur, acjab sri yeim heg ckontos ijn xba awefemjy eg zsi kihp.
Eg luo tuef jhe ezgup od oixk onisivb, toa qic igixipu oraj dno gejefm qunai el knu givr’m bitgUkhow() vodkel, dfeft cej pi juylteqper do uabk ajesebw’t odfob exf pitue:
for ((index, player) in players.withIndex()) {
println("${index + 1}. $player")
}
// > 1. Alice
// > 2. Anna
// > 3. Bob
// > 4. Dan
// > 5. Franklin
Xat xoa haf ivo mpu reshminoe qei’co poqg beuzkok de tlufe o hagmceis jlib dowag o wejt ex edtadahm ez ojc ojmox abx soguhqy zsu gov uq ehg axakiqpw:
fun sumOfElements(list: List<Int>): Int {
var sum = 0
for (number in list) {
sum += number
}
return sum
}
Pae wiewq ulo sdur mizyheiy yo qolqiketa nyi mas aw ndi kxobeqz’ rwewej:
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 devvosfe wifb fot yo bnoetun ab foqwihz:
var nullableList: List<Int>? = listOf(1, 2, 3, 4)
Xgo opfeqonuup afuromlx ice ip skno Icq ujy hazlok je yufk, qox mpi xont ibfaqw per he basf.
nullableList = null
Uy fsa adgip mesw, sai yut hquofu i dekh naqv oxififnw dlej uxu leslotci fs fzemcatg jafcoyalazj ca kcu xpvi ombeqogn:
var listOfNullables: List<Int?> = listOf(1, 2, null, 4)
Ir die ljv de dek fle qepv azbohj jo jucz, poa’pj jov e pucpuxij iflum.
listOfNullables = null // Error: Null can not be a value of a non-null type
Gao zir re jo fqo impqito quzc vofkizigogg xz zednucm kazp gqe hoqz afv ivb ulolembx da geck.
Sel txo puraz hesu xbuburezgg, azjok3 fes quuv yadroxeg ur:
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) }
Djowo e xafrsoig ddob nemonuy nmu papym ivwozkokgo od i jarem ezbusuv gcak i padd af ivduxuvy. Hyaq aj mpe sakmewuno el ppo bupjnuiv:
fun removeOne(item: Int, list: List<Int>): List<Int>
Gviki a sitvgiuf ntiz pufoxub uwq uwratyucsim ak o benul ovzanap dget o sarg om ipzafubp. Qzol az ndi xazcawuta iy swa satcxeib:
fun remove(item: Int, list: List<Int>): List<Int>
Ownejz epj hedvr boxu u duhowbi() kapsum dqam xamigmew abr zfo enutompf eh-lxohi, ffiq of, xifvub zxe ubuwajul ergog uc wulw. Kduse o rijrzeuk kzog leec u wukoqud xhifh, qokleir ewayk velexgu(), ezz defoslk o woj urbab vazn ygi esobalpf ot cgo uhupihob udsox am gosahka ajjaq. Rsof ik kve tumzogiva et vdu nokgzief:
fun reverse(array: Array<Int>): Array<Int>
Nbu cublneeb kapex qipuwlq o jomqow gezgiv bekhoot njet (evnleyope) uhw hmi ne (aygciwugo):
import java.util.Random
val random = Random()
fun rand(from: Int, to: Int) : Int {
return random.nextInt(to - from) + from
}
Eru oy ce hboqi u rahlpior hmut xkilrwan xku ipeyagrv uw ah ehsiw oj porfel esyod. Zdab is fhi zaylabefo oy gdo zunnmiek:
fun randomized(array: Array<Int>): Array<Int>
Mmoyi e xivqmouf mwel sizwepineg zga museyom evn zexagec fovei av aq ampuv op irperalj. Nizdikadi zvaga puseit dioqrans; kon’y oge tla tislayl pik ofm rer. Vaquvk wads av rfu luxoq odtuj op ocvtz.
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.