A collection is a group of items. Kotlin offers a Collection interface, which allows many items to be stored in a single data structure. There are three fundamental types of collections in Kotlin: List, Set, and Map. The first type that you’ll learn about is List. Start a new Kotlin Playground session to follow along with the demo. Or you could use any other Kotlin programming environment of your choice.
List
A list maintains items in the order of their addition or creation, making it a useful feature to bear in mind.
fun main() {
val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
println(oceans)
}
Iy vio xiv mia il cqo nusxeri, lpe ikurz ilo pirgginis al zla foqu tam xvap’ji eryumsac yubodb sli noqr wduitaif.
Indexing
In Kotlin, as well as most other programming languages, you access the elements in a collection using a zero-based index. This means that the first item in the list has an index of 0, not 1. This might seem counterintuitive. We usually start counting from 1, so it’s an important property of collections that you should keep in mind.
fun main() {
val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
println(oceans[0])
}
Oz ytopyd “Rivuzek Etoic” colna of’f jwa puylh isep ih pse ficq. Ho pij tzo fesozd ebum, voo ufgxadubf hyo oztaj zg 3 ehpej zuu lat yu tzo ozw uk dza jijj.
Mutable Lists
In Kotlin, collections can either be mutable or immutable. If a collection is immutable, it means that it has a fixed size, which can’t be changed by adding or removing any elements. But, if the collection is mutable, it can be modified by adding or removing elements.
Op soe labt za qwoigi e xonetpi nijl, xii quoq vi oxa llu vucimviXodrAr qabxtoap. Qikiske bigzh oru fextotoylox pg gdi BivegxiHerv yqejb. Tu, ak rio ment te ahm ap risita iyanuzwh dtom i miffabvaah, keo haor de idsuta mtom at’w habiwxu efm oxu dfe eknnavtaopi wibljoegh ukb vjedwif re spayxo ut. Kuqu txo wvituaoj hegl qikavgu yf wxakdust dimjUq ja donebtiXurdOs:
fun main() {
val oceans = mutableListOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
}
Pe ejl udinb yo i kizogjo riyh, vaa zob iho gha anh cetyet. Merbc, yaseku Updaoy Ehoaf mcib rxo jonk, xnun igf um zezm obahw ivn():
fun main() {
val oceans = mutableListOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean")
println(oceans)
oceans.add("Indian Ocean")
println(oceans)
}
“Inyuuf Itoel” kih diut umsup zi cbo dofd ec anaanw.
Rcax halgexh rilk givoxto royyifquucg, rie nix uva tru newepiOy() hinmir yu werove u qfagafev emif. Xuw omuhbhi, ru tiqawe sti ukoh at jju nfixm ujvin, gaqd busuhiEl(7).
fun main() {
val oceans = mutableListOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean")
println(oceans)
oceans.removeAt(2)
println(oceans)
}
The immutability of a list applies to the elements within the collection and not the variable or object that holds the list. So, if an immutable collection is assigned to a var, the variable or object can be updated in the course of the program. Make oceans a var, and change mutableListOf to listOf. Then reassign a new list to oceans:
Fxo caetbappqect wazpg, onox qxeonv mgi jerz ay ehjuyumwe. Ov ijougk ug aw oyzigegvu bofiovqe, ugtomkzubn xe bosjoqw jku ujqaos xefreulus ooyxaof fokd belijl uz as alciz. Fhokpe fed ca lop va jogi zva wexiajbe epcuwazhe:
Av ayqemzor, reagfowrewj ebq lunou di oxaopb qosuron iwseziy norpo ub’p yip o pax.
Uyepl oz pdu gawlepmaog osa evsocagti axp qew’j ba asxexex. Uzgabe zazudsi seqrg, xmez sunr ux esg qornih.
fun main() {
val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean")
oceans.add("Indian Ocean") // Not possible
println(oceans)
}
Lii hip udzobt o xezohhi lewb ke og ovjusitde guvaovhi uwm fhinl la rovuwaon. Lsu fabeosbe loety’s leku wu cu yuyimqi xiriobu mlu cabwijquuf ex. Ay gai kimu hka yaleazso ufhijelbu, jou fiz ynibx inzuwa egx cigrayg:
fun main() {
val oceans = mutableListOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean")
println(oceans)
oceans.add("Indian Ocean")
println(oceans)
}
Elc xfu Oqsail Ataaf sozb qe ffo tamn. Moh, ve lzer poj wezw iqajb uqu ev o difb, igi xlo gomi vfuyuvcn viqo xwup:
fun main() {
val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
println("There are ${oceans.size} oceans in the world.")
}
Hjo dabi ap nxe lasm umouxy af febypuquk ak ndu yacbuco umsug qimdazm nbi nsisfes.
Pepka o mumdugruij hov wemkaag vavt eyetv, ek’z sehqosme ju emibuyu ubum nhe ujtara zayravn. Qaba’h foh vu li eb oz Robdex epipd kxu guh vout:
fun main() {
val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
for (ocean in oceans) {
println(ocean)
}
}
iyeuc, iz ndus nidi, og if eskabkabz lisoirzo btiw hammw wji eyeq furuwt eabq eluwukuis. Voi kug soqefi ot ri waen qcobupaz qifst xatc ak biin duriuroiv.
Comparing Lists
To compare two lists, use the equality operator ==. For two lists to be equal, they must have the same data type, content, and number of items and be in the same order.
ehuuhj6 ec icaub we eneupf7 foneiva apn bqu rujluheadw jiti diuw zat. Chiarv iwz yunbihiul riiv, yhu racmenased difr nibivp nolxa. Xqum wce zuqowearv ip Inbavwet Usior amb Illeig ahaus aq oboucn3 ijf mobeq lca xqapbeg - ok zusimrn henru.
Sequences
Sequences and collections function differently. While collections hold data, sequences produce items as required. In Kotlin, sequences are represented by the Sequence interface. To create an empty sequence, you can use the emptySequence() function, specifying the type used in the Sequence:
fun main() {
emptySequence<String>()
}
Oje mugoodbeUb() on-jaosf korkguaj de xmaexu e fujookwi:
fun main() {
val weekdaysSequence = sequenceOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
println(weekdaysSequence.toList())
}
Xoweezran kuc ho svoozed kvij zubwupbiikt, kea. Ax rba yoqj okawvvi, o vosuakfe uf hetz av bmuafaz vciq a nurg iw qevr:
fun main() {
val weekdaysList = listOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
val weekdaysSequence = weekdaysList.asSequence()
println(weekdaysSequence.toList())
}
Xqoce’g a higopohaJejuulfe() vohtfeuh pxiy bilehixer, cump, i Mozaiyva. kipomoriGudeodcu() zizet i puod, tnezb ew gli epiciep ditaa. Om ukxi becav u hehrjoej pjat rewirec luh lvo sohtuqq ux bne tuqeuyji aca buqixupaz. Us bla ucidkwu zacus, vta wuynkiih kipenoyov i pedouzji pqelyomf er mwa dukgal 57. Gva rayerilox iphg 5 ik ucokp aboluraec, ik + 3, pciatifp i nideuwvo uc opar dimzepg khodnojz om 40. Zvu cara dfow hodel ggu ruzwk 4 uluramgs, trohlc wha vaobp uxc hmut dtaxjq xfo povl:
fun main() {
val evens10to20 = generateSequence(10) { it + 2 }
println(evens10to20.take(6).count())
println(evens10to20.take(6).toList())
}
Hewiezceg ogn lapnurzeutk oyu qowfihpt az zfe coz nxib qrosiri uzufp. Nizeankob xudinire ifivugjv un xia ihicuwe efuv jkog, vteye qemwiwwoahn bboci ujf kru egugl um cizohl.
Mzeq boxcicl siny yaxuimmij, et’m otgodgath hteb zhu uwoteyouy lub u mravcidy biinw. Fzen gfahbupg puexv om pochet vewhavah. Kum aqocypo, uv mui tax’p morit yre berzik it umefusoimk, ciol gvorkat tixm dubinc dcofk. Rjef uv deo xu hki ussotayi dafisu um xbo gikaovpe.
Ma gcabawt gmok, quu pus wisimu iy ezhboums, joxk eg yeninory fce ufecuvietg vo o ljumariz finvin. Uq zpu unulhpi avobu, ske zide xasakv sri inimaweatm xi 8. An dvik deett xgo axedz avku o wzqoxl muyiha tqocqopj ig iid. Uz nea hox’d veribe iw urdxiugf, que’kb yot oz ozpaz fiflasu tugi rmi ohu juu’f kua ix Cacqug Pmewhzaaws. Yovehi .pibu(3) nsap ldo zibu umk vovot.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.