Collections – Kotlin’s version of arrays.
Since I really don’t have much time for writing each description, I’ll exceptionally use lots of quotes from other sites, sorry!!
From this point on, we’ll go through Kotlin Journey again. For the past few days, I spent a fair share of my time somewhat learning Python, but I really need time to learn Kotlin to start building my second Android app with JetPack. Anyways, without further adieu, let’s go!
And to save some time, I’ll use quotations from Kotlin’s official page (kotlinlang.org) for descriptions. This time, we’ll go through collections.
listOf()
List is an ordered collection with access to elements by indices – integer numbers that reflect their position. Elements can occur more than once in a list. An example of a list is a telephone number: it’s a group of digits, their order is important, and they can repeat.
kotlinlang.org
collectionSample.kt
fun listOfCollections(names: List<String>) {
for (name in names) {
println(name)
}
}
fun main() {
val myList = listOf("Sophie", "James", "Alex")
listOfCollections(myList)
}
$java -jar collectionSample.jar
Sophie
James
Alex
forEach
collectionSample2.kt
fun listOfCollections(names: List<String>) {
names.forEach {
println(it)
}
}
fun main() {
val myList = listOf("Sophie", "James", "Alex")
listOfCollections(myList)
}
$java -jar collectionSample2.jar
Sophie
James
Alex
mutableListOf()
MutableList class is used to create mutable lists in which the elements can be added or removed. The method mutableListOf() returns an instance of MutableList Interface and takes the array of a particular type or mixed (depends on the type of MutableList instance) elements or it can be null also.
geeksforgeeks.org
collectionSample3.kt
fun listOfCollections(names: List<String>) {
names.forEach {
println(it)
}
}
fun main() {
val myList = mutableListOf("Sophie", "James", "Alex")
myList.add("Tommy")
listOfCollections(myList)
}
$java -jar collectionSample3.jar
Sophie
James
Alex
Tommy
myList.size
collectionSample4.kt
fun listOfCollections(names: List<String>) {
for (name in names) {
println(name)
}
}
fun main() {
val myList = listOf("Sophie", "James", "Alex")
listOfCollections(myList)
var listSize = myList.size
println("the size of the list is " + listSize)
}
$java -jar collectionSample4.jar
Sophie
James
Alex
the size of the list is 3
myList.get(0)
collectionSample5.kt
fun listOfCollections(names: List<String>) {
for (name in names) {
println(name)
}
}
fun main() {
val myList = listOf("Sophie", "James", "Alex")
listOfCollections(myList)
var listSize = myList.size
var listSizeNum1 = myList.get(0)
println("the size of the list is " + listSize + ", " + "and the first name is " + listSizeNum1)
}
$java -jar collectionSample5.jar
Sophie
James
Alex
the size of the list is 3, and the first name is Sophie
via: