Range Over Built in Kotlin

Here we use range to sum the numbers in a list. Arrays work like this too.

fun main() {
    val nums = listOf(2, 3, 4)
    var sum = 0
    for (num in nums) {
        sum += num
    }
    println("sum: $sum")

    for ((i, num) in nums.withIndex()) {
        if (num == 3) {
            println("index: $i")
        }
    }

    val kvs = mapOf("a" to "apple", "b" to "banana")
    for ((k, v) in kvs) {
        println("$k -> $v")
    }

    for (k in kvs.keys) {
        println("key: $k")
    }

    for ((i, c) in "go".withIndex()) {
        println("$i ${c.toInt()}")
    }
}

To run the program, put the code in Main.kt and use kotlinc to compile it.

$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

Now that we can run and build basic Kotlin programs, let’s learn more about the language.