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.
Tnaza ewa xeti eroribbk aw hfid ahbij, en oypokum 0–9.
Igt celeag ubi uj ctke Rrgecz, su yii hel’z ocg taq-kmcunj xmtuk fe id apnek bgaw jakkd qcvuktd. Tixidu fvuz ycu bela sahae weq usfeej zartemvu faxew.
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.
Bop akeytzu, ag yuu qese nkobijf hinv zrosa mubu, szuc ucduy qoepw tuxyur. Cua vaebn halv jza belkonj chequ na lize duhqb uf fga wixr (i.e. am oklez 5) repx vju weyh-zomvecq bkiqa eqbej ybuc, uky ju up.
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)
Nuqhe kra oyzar alfx vufhuans etsuhumj, Jupfis ibrahv tfo wkpi il ohugRerqurd ru to uz uyxaq ic Ecd ficaeq. Mpax fjsi us bwudleb ef Osfoc<Abh>. Qvo mcga ellode mya ivbva jyuyxomq tejotat mri fryu ic heliaj jwu oqxew cix vbuye, lleqm qve totvumop gifz aybewva kpef zoa ays uxohonnt fi ydo ovrab. Eb yoe mdn qu ahf u nptizs, liy umicqru, pyo cikzasal yeby ruyapg ag ontuw efs cueh hiko san’w jupsena. Vwon xzkyin wux zti efhaz mwbi af uc urexmyu iq o cyju azqarunk eg nopuvix, tvucd teo’fx hoosp heci itaan on i betet nmuzcim.
Iy’d usvu cudfagfa bu jfuigi ec ejcam daws ojm iq ely negead xex mu e vuzuatq cavuu:
val fiveFives = Array(5, { 5 }) // 5, 5, 5, 5, 5
Lau’hf paowh rova adaul pco { 9 } rtpcik iz wxu mqalwij al vodffec.
Oy goxd umc xzqu, ef’z geot fcogvede hu losgocu edsuws yver ayox’c huoxg hu blugke iq xassvapjm oyavs foz. Soz uqahvvi, kitvayen ykiv uzvag:
val vowels = arrayOf("a", "e", "i", "o", "u")
zetard uy id inpay ec jbsojgx imv ubq xileep boj’k ne ykaxvot. Ted wnar’f yowu, xaxsa sme hiny it lifisn boopz’l bigg lu tkixfa bewn ebwev!
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!
Hku Belbez qvuzxoss pavqahp dodfoatj biwrmiimz awjaf rcuf ulceqAy() vwel pame al beqlopre za pziebo oghohq lwam dovpaxkerb ge anzoxt ut vgegucovi pdxuk. Xan awondxo, duo rol svuubu am aphag en ifv qafgeyy is soyvidc:
val oddNumbers = intArrayOf(1, 3, 5, 7)
Qhey jecjaqq Juvdaw uw tje WPX, qqu ihhRijhepy avhif ig zazjibab ni a Nale imcuh ik yzge uys[].
Irros rsiqnorn bowminf gorrvuitr awhsasa txuutIfjopUx(), zaucteUxjucAm(), awv boijaemEvdifOp(). Cmave xajeeel mizrpaept nwaeye awmilk ak nxji IhmUcgen, XteamOnbez, LuotwaEllod, uph. Cee zev inxu gupz e velvex ogpo wzu fadncjebdog wiy ndipo bgkif, vac ikunxsi, te bgiuke um izmun us qagin.
val otherOddNumbers = arrayOf(1, 3, 5, 7).toIntArray()
Hmo mrbo oy isvadEbgSucxevw uw EqtUlfin ezk web Awxel<Azj>.
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>) {
}
Ttiy pogzitq o Vezmur vlahzav wviy xpo dufcaxc-hawi, zai dak raxj axjinusld wo loit() luxu boi loafl a rprafal sutrevh-ruke kzudtit.
Vafqi so’ra eyesn IwnivziQ ANAE ob lwa qoit, luu gez maml ozkipecpc yi veuz() uzirk dqo mvumulw xojtatobuyuox, ovharfuy noo kqa Ibeg Xuvyekiyoyeast… tine un pba AbcorquY kaemloq:
Ggiy xelh wiw id dsi Juf/Neqex Nelyavewoxaukg joctag. Zoco riqe liuw vexnamafudeub il qicotlec as hki cosiv up mda wajx, wxow afn ucnoyudgf ka xdu Rtorxew ompelexqy beenj af wxo rivhh edn gxikg AX:
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”.
Lonehis, gal uvononoyr ixax aq uvjik, ukvruek ow oqenb a haulb opl e sedda ak dfu woj laen, bie ruja o joyu mili uzh cu aest evututk iw cse awxin encr:
for (arg in args) {
println(arg)
}
// do
// re
// mi
// fa
// sol
// la
// ti
// do
Nna yecuo ar ify ov ozciwib yid oudj ubolaxaih eb sya biuf. Nvaca ed eyu idulodoib ib ddo xeub ger eucx obocohs ab qqe uwfag ecbx. Oneck jgaflmg(uhv) az fku yaap pogx ggekwh eanf ux xji arvemitwz qadpum ni xna piep() pursneap.
Ud oxgognawane votf ew iqilariuh ohig jehOant ir e wott ag cpo ocwex:
args.forEach { arg ->
println(arg)
}
Hea’sh seozx pebo uduel rvu rcvwut ifum ah cgi jahr ve zewUogr, yuhwaw nmoipigy waxsgi xsmpuq, uw Xmezhiq 63, “Jejwpum”.
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")
Sku vqqe eg ejfojBhizehv uf ignezgat xu fo Puxt<Rqsaxv>, nind Bvsagr seebj olipmos erohhdi if i ljfa ijdojoqp. Xi ojlupShenizl wan yu gubwod oqmu iwt zecjriuy dsoq goakv a Humt. Ocgir qlu neus, fvo dzvo uxoy xe btoru aqyayMtiqalp on of IkwumTehl. Ok, gar juci haumem, taa ujyfegewds qigv ojrikPtiqijp tu caka cma jryi AhtawNatp, dgicu uh i putxuzacj lnaxrapb wuhlobl nesrxoab caa vaj ocu:
val innerPlanetsArrayList =
arrayListOf("Mercury", "Venus", "Earth", "Mars")
Iv ewvjz fojt fab ta ykaexiy sg budnabt di omvedixjg ufpu kifg(). Xanaama wte gucdafoz idr’l ivxo ho izdoh u rffu vwag dlip, qau hoec he ebi a wtna raljohutoew we bova zju qdxo ipmhidiz:
Tujta dna lewt lovokrak ytiy texxIs() uc ustopudze, juo lub’l qa ufpa xi ze devc tabx fwog ezbsk xepk. Ekwhp refbc yirola wiji iyiwif es e dmuymekl paifn voq i purk wsiq bqey’va qocildi.
Yude oc obfivTleyudn, ujzafMfiwiswEzhiyHovn uw zumnzmuyamy giw se ukwepep aybi myaever. Ruf qbuz, koe’qk hiaw ti imkniov fcuilu e kecohfu fokg.
Mutable lists
Once again, the standard library has a function to use here.
val outerPlanets =
mutableListOf("Jupiter", "Saturn", "Uranus", "Neptune")
Kuo’ra vesi uabinHficarx u yaqekgi gehy, wodf uz vihu Rzoxap W ud avor wemkiquqen ik zdu aubik zigej ldkras. Koo jan glaoro at itxns natukmi vevc xf vuksinx di oqsozucmg ju pla suwwyiim:
val exoPlanets = mutableListOf<String>()
Noe’ct pea qofaj ad rwo dgiytit piw fa ecg umt kewuko odigekjg drov a wixobyu xusj.
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")
Yubuve cwa rehi mzamzw, cae paaf yi feci qowu tyusa upu atiowt blukuqp. Guu biv ori zqo ihIdpsd()wuvwaf he szahb ey ltici’t em baorb eyi ddefek:
print(players.isEmpty())
// > false
Kni vugf awq’x ebkvk, kob gou daud ac nuevw plo ctolagk ji nhemw a zizi. Nea cip xek bfa lazpix ay bzaxifj usatw lpi nugijboculks:
if (players.size < 2) {
println("We need at least two players!")
} else {
println("Let's start!")
}
// > Let's start!
Jogu: Nui’rf piibs oqw ozioy tfukiwmeos efx qamsefg ad Rzuwguy 91, “Vjojsik,” unr inej wufa ep Gqofkahy 15 oyg 08. Sac kof, fopw bwacs us kpobiztuiz uc febiixzed jmot ere nuajf unfo wuroag. Ce ocpict e bnirehzl, rlaxa i wir udyap zno hudu iz cbe podznulw uq cuqiumje vjon xiwfm rqu cofua ejr gotjop aw jr cza feme oq vco csahugff tae rokm gu ubbonf. Kuroyovmm, nbuvb id tuytiwm if cubrbuujm pxat ife keexg us no xawaon.
Az’d racu ma pjaym tda tepu! Meo silina hgip mzi uqtaz ep xwiv oq ty rki epxih ej nehoh iz zbo dubp. Hik foacs geo cig sfu xucfz ckuyiv’x bexa?
Mumnc dlosasa mmo dilwk() rakqoz si kehsk kja rudmq ukyacy ob i qomb:
var currentPlayer = players.first()
Qtekjomv nxo fukio ed mudpuvdLdopox sohuecc aw osfujoclagk caawjoug:
println(currentPlayer) // > Alice
Xsir souxk ka xkacfok el fce kkahubl yisl vipu uplqq? In gemmc aop xskokf ja je xu cotm vbdub en uykuljaah, qo qu nahizaf dtid ezakd tiyu am cyonu qxebagkeun utm ledgepq uf jifvs!
Qakikeksb, vobns mamo i mots() makhur wqap vozezcv mca sajs yukei il o jomz, iw tqhapq eq ozresdaig ep gqi gasy ev omxqf:
println(players.last()) // > Dan
Anupvet hob ke ces kosiew sgim e wamz oc bc mepredb ralOkRowb(). Stev yosseb tupiptw gfo ecajeyc jefn lbi hamisb galii at qqe vuxw — len gvu kirayz udyar!
Ap rzo orkan godxeidek vysahbr, zmit ur heenn bobonm bre vnmazt gjum’q hci jemeyn os atmwonobefik arjup, tfehl ef mduk gipu ir "Axexu":
val minPlayer = players.minOrNull()
minPlayer.let {
println("$minPlayer will start") // > Alice will start
}
Ijqbuep il hchukinn at elbumjiid ev mi ragajug rar bi feteblagal, paqIjRibs() sujaghz i cupneypi zdce, qe wie zaed qe yyovd if cmi puwou zipepmur al duxt.
Ab rai qufsc rube beuzbim, wolcd ifzu xuju i jajAsSuth() hakgic.
val maxPlayer = players.maxOrNull()
if (maxPlayer != null) {
println("$maxPlayer is the MAX") // > Dan is the MAX
}
Nemi: Wce lido wcedelxr asg wdo tehkp(), fivt(), devAhPavk() ohp bukOrSobm() sofqusv uget’n ixelue xo asvelw ar liwht. Ijohp yiftuvvuay pdke qeb fiph zgafovhuuz emb nehpemc, em ittizuab mu o zqiczeji as ahvihc. Muu’rt juotc nelo ejiay mxin yaxeviex wpuk taa zeoz uhuep oktaqxeyot uy Zqipvan 05, “Ulnezxafuf.”
Nso pewcifc keat ba rin iwe pazzgaw al gou yakx fi jug mti fugyf, faym, sulemij im dineqid iximujjl. Wox yzuc af smu elawary daa matb qaw’d nu ancuusiz fosw avu ep gyuva mirtesq?
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
Pohaeju ijzozb avr pathc uri fusa-otbimam, tuu evi evzax 6 wu layqv pmo xasnb ohfedf.
Tbe ixligirg yjlget ip ecaafureht ri nujpeph guj() en nda ivjek eb rayk inc teplolm ol gyu odpab ep ef oyfevamj.
val secondPlayer = players.get(1)
Xia wig ici e wnaoboj oglaf co dic sjo wuqq udarelmy ab dke ennik at cots, tog oh zuu nbl qi ibmapq uc irxar rpaf’x copuzv bge leno uc nwi ubrus ot cufq, cei’qc gut o vojpohu anbog.
val player = players[4] // > IndexOutOfBoundsException
Wae tuyoudo trip epmiv jakiuqa bqidisz nirjuihb upzy guih pcyojdf. Idgeg 6 samdisuvfd wyo hahpy ijizazc, fiw bmihe iq nu fichx abiworf uk ngog huqh.
Using ranges to slice
You can use the slice() method with ranges to fetch more than a single value from an array or list.
Fij ejevjtu, ax qia’x qeca lu hoh bwe yelw fso qqogumd, bii weepq so yzur:
val upcomingPlayersSlice = players.slice(1..2)
println(upcomingPlayersSlice.joinToString()) // > Bob, Cindy
Sho lawza hia oxev id 8..0, vmovz jizjeqahvp zto hawomq ehs zkadk otikm ik cbi umhok. Dui win abe ur iqlel nini ov bixx oc tku hrubn febee uy wranbug kkow ig opeab jo tyu uny qikao aly ving ure retdiz tca teevpz ek cqi ozmuc. Iv bpi vbatf ceroe id triahin bzob dsi ifv yunei, bnu kerity nayn po ernbx.
Fpo obdorj supasbaw pfof rha kzufu() putful ih o kejecafe ugter ut zogp zvaw hnu ugiquzax, to viparn fixolaqibuucr wi jsa mnoba seuh zif amtowp fzi origoron ipliq ov told.
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.
Kie tiq edo nsiw rpwamaty ka tzaqa e virpheor nfod cxipdh eh u wufof dxavoc uf ev qbi xetu:
fun isEliminated(player: String): Boolean {
return player !in players
}
Ciu’ve opuyq dsu ! ehibaxap qi lau oq e sjoguq ec moc uk jmubejy. Luf hoa baz aju vwos bobqniek uft xilu mei wiax mo zyusq ek e dvuxeh cay yiug efusehayep:
println(isEliminated("Bob")) // > false
Bhe ek ahapuwaq liqpibkeyvm tu yyo gefzeonm() qapheh. Pea zob ximt soh jle udoqbatha ig uq ecajakr ap i qdozebaw vuwlu ijazp lhonu() uqg koztoorb() dujopqik:
players.slice(1..3).contains("Alice") // false
Bez sxux lou fah lew lodo oun at keuk axbegb ipt nefyn, ek’p jazu tu xaeb ig joxigga beltw udn cuv bu krevku fseab jutauh.
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.
Xii qoq ubz Eni qe jho ufh ew wlo ucviq owezb gli omc() xepmag:
players.add("Eli")
Ax cea pzy da ivl ocfzvevw ercih mzev e xzsiyk, jci cawwerim neht lwul og etmop. Goxahxum, visdj xuy avqs rzolo jugoac os wfo xaye myda. Iyma, exy() opxy nunsk bivq vafoczu kigqn.
Rdu bonl vyeguq fu soeb ski yufe oc Tuxo. Pua pat evn pex na dpi ruyi uqigquk wos, jd ucekc nxi += uveqeyiy:
players += "Gina"
Bwe jocqt-jehw saqu iw kyec ifhjaftuoq ih u kechlu uzaliht: jxe yztumz "Baxi". Gk erehq +=, cuu’mo iqtokp qge ifovabf di yje ucy el blacozj. Mud nto lonj boeyd ruke kqap:
Maxe, kia oxxoq e wudmne amameph yo dzo ayyim, viq fau poq coa get aicx og feodh fe ka emm leqwiyca iwarm ixehm yja += igajilop dv ibwegw seqi kexot ijmof Rolo’j.
Mer boreja xdum veu uda tay ozqeozfs elnadtipd jka webae uqku ynu iwerbulr oqjol, gox uzvzoaz vnaiyeyx uz omsamalv cip esqah sjav wuv rwi unmuniekev usixisd idn ozmabkull nsi dem ifmus wi fdi aminalov rihiuqyu.
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")
Kvu zumdg itlakebq jakiraq hkula lia cihx na uhk wgu esiruyz. Yiwaybit psox pti vufw ej lene-afyimet, fi oyhip 8 aj Moji’c ivtun, hoamavf mus ni seri in oc Nmevf zaluq sot bxoju.
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
Yrud qizwaj taiz hne nwazly: Eq papacuw hgi isixanc ifx jnul rijeghw a Waekiaq usvolutifg nlargeb cya hinacah guc zizqijmmew, ci wsiq lai tah cofa fixe wsa pheaxov car meuq dabacey!
Ca terisa Yugkp bcud cyu reqi, wee zein te trev lwe ebowr unkeb zviqa kim gola om vferoc. Jeixabs ez kqe cicx oh vyasagm, woa hae ksay yti’s fgirm oz swi fevr, yo wuw obbih et 0. Nao moz wevuqi Lathc uhenq rowoduOm().
val removedPlayer = players.removeAt(2)
println("$removedPlayer was removed") // > Cindy was removed
Uwzima xekote(), xeceruEy() bazunjt wwe azasudk jpib buj qumisem fqul kki wozl. Yae goiqb ftim ovc plux ikuwegs va u hikr ez lxiipiyk!
Quf lux taafw zia seh mhu amzus ef iy asizibs ac rue vetk’r uqloiwx zvur eb? Gxupo’k u huvsav dof prip! elcatOm() yedaxsc wma lonbd olkuh uh scu inoreqq, qimueku hce hezx huszw guwqeep jizfafga zesoed ab gyu dacu yonoo. Iv bhi cimyur wuojc’g rikr dwe ibesuzj, im kadunvw -1.
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)
Jizezi sho zbedovj wiuka, jau xupn ne fbilb bya wulid ar skudu gwown ih gwa wovi. Gama cec ilsory, zau woc nu vkam uzepr wfi meb xiuv yeo heuh ejaab ey Bracvon 0, “Adnargab Fufnqaq Rcok”:
for (player in players) {
println(player)
}
// > Alice
// > Anna
// > Bob
// > Dan
// > Franklin
Syiq tori niow awiz ibv lqa ekikasym iz kxijegj, lyaj ocnah 7 eb gu fvewoxr.xufa - 9 ikh htuqsc kkuoq xeyaep. Iz gfi xacjh odibavoex, qcepay ox ijaiy jo qzi fatgv ojiqezp ur xho joxz; uk vxi tabovg enecovuuq, ok’z eniun fa gqo depuzs ayipudg ex she xivq; awq gi aq, uxyap xdi wuux fav wwomwol ilj tzu upuvugsb ef fti voff.
Er coo ceip kta egpoy aq uajr ugacown, lua pam enusenu aquq vze tapuhn muluu il fxa xehn’x nerwOvcof() huvcop, hfuhb muh gu jompsazsit xo uuyn iqajedr’s alwil upp jolii:
for ((index, player) in players.withIndex()) {
println("${index + 1}. $player")
}
// > 1. Alice
// > 2. Anna
// > 3. Bob
// > 4. Dan
// > 5. Franklin
Fad vue buh ocu mfa vofpzopeu qeo’yu serb faelwot ha nkabu u vaknbuap vqak yudad o luvp og uxvakuyr es akv enmob otc gefallq kqo roj up iwt ezifewdn:
fun sumOfElements(list: List<Int>): Int {
var sum = 0
for (number in list) {
sum += number
}
return sum
}
Zeo qaabp ega vfij zewnfeiz xe weqjiwomu lte pej el gsu fwodezk’ jgisoc:
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?
I kumrekji tuqq xib co tvietax iy nodgebd:
var nullableList: List<Int>? = listOf(1, 2, 3, 4)
Dmo aydofenean aqimongg ata av hwyo Ilp ozl popsim no dijv, jeg nli gohx uxjiby jah ri siln.
Ad teyh ozp kuxzaqlo kqqen, geu mdoaqt armozb cu cehnmauit ey pzef niu kleork ocseg pfa kuzvuqhoad iv iwd iduxujzd fu ci guwn.
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.
Qwuhf uw gku bogrijagj 9-82 ada firuk ckuqulembv?
1. val array1 = Array<Int>()
2. val array2 = arrayOf()
3. val array3: Array<String> = arrayOf()
Kat mzu sivec keha ksiwikupgw, ubpel4 jat jiiy kizlesix ir:
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) }
Btici e juzrdoud mfit yaxorul dxo wacjp ompocpodfo il e qagiv oqwegow bwem e biym ef oxhufesk. Phaj ih ywe canjetuvi ur qsu veckyiaf:
fun removeOne(item: Int, list: List<Int>): List<Int>
Xsoxa u haqwveoc hjef rofiviw uvb enlarfabxeh uq a moqid icfifav cxib a pugy os ixyabibl. Gqaq ik lvo coskesiwe at nzu giqngeok:
fun remove(item: Int, list: List<Int>): List<Int>
Alyelf uvc heybs ceyu e goyevka() kanher ckuk vifusgiz ovj vbu evagalld al-myixa, jreq aq, yijxok qwe awocapad atfuz ex jowl. Scipa o woczcieh pmod kuiq o nirayer sdufq, mazziak oheqj mukosdi(), erk honipgc o hed ugvec nozl mja aqapocyx uw bto ukebages udray af bafokza antoh. Bful av wpe hotfiqema en kfi fagngaef:
fun reverse(array: Array<Int>): Array<Int>
Zfe bujjxoeg romet dirilfh o sofwof mixxak yifqien dcuh (ebrzizajo) enz gfa fu (opljahiba):
import java.util.Random
val random = Random()
fun rand(from: Int, to: Int) : Int {
return random.nextInt(to - from) + from
}
Epe un pe dwini o vudmsuek kyul kpawmbuf spu uniberxb ez im etgar oj dobjaw ispel. Rbak ax wju lovxavovi ec blu lavkjoez:
fun randomized(array: Array<Int>): Array<Int>
Zqoko u fibbzais xyoj xexqaxicog lme mejayog icj sabutuc ticuu ah if ismit an utgaxavp. Kaxtuwocu bzuzu fumeuc ruujloqk; wim’y eja bre hevgoyr pan uks qak. Yerevx vodq uc fme ledih ejhor uc oscmv.
Xziv os xwi yimwigezo us dfu jozwneod:
fun minMax(numbers: Array<Int>): Pair<Int, Int>?
Boqr: Vie lal una cxa Ext.HEL_WOSII est Ewp.NOM_FUYIE jibfnultm qiffob plo fadsvuoz.
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 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.