Monday, 25 September 2017

Iterate Over Lists in Kotlin

Create a list, add, remove and then iterate over a list.

fun main(args: Array<String>) {
    var list = mutableListOf<String>("zero", "one", "two", "three", "four")

    list.add("five")
    list.remove("zero")

    for(str in list) {
        println("value = " + str)
    }
}


This has the following output

value = one
value = two
value = three
value = four
value = five

Iterate Over an Array in Kotlin

In this example we create an array, called array. The contents of the array are created by using the Kotlin arrayOf function. To iterate over the array, we use a for loop.

fun main(args: Array<String>) {
    var array = arrayOf("one", "two", "three", "four")
    for(str in array) {
        println("value = " + str)
    }
}



This produces the following output:
value = one
value = two
value = three
value = four