Range Over Built in Scala

Range over Built-in Types

range iterates over elements in a variety of built-in data structures. Let’s see how to use range with some of the data structures we’ve already learned.

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

object Main extends App {
    val nums = Array(2, 3, 4)
    var sum = 0
    for (num <- nums) {
        sum += num
    }
    println(s"sum: $sum")
    
    for ((num, i) <- nums.zipWithIndex) {
        if (num == 3)
            println(s"index: $i")
    }

    val kvs = Map("a" -> "apple", "b" -> "banana")
    for ((k, v) <- kvs) {
        println(s"$k -> $v")
    }

    for (k <- kvs.keys) {
        println(s"key: $k")
    }

    for ((i, c) <- "go".zipWithIndex) {
        println(s"$i ${c.toInt}")
    }
}

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

range on arrays and slices provides both the index and value for each entry. Above we didn’t need the index, so we ignored it with the blank identifier _. Sometimes we actually want the indexes though.

range on map iterates over key/value pairs.

range can also iterate over just the keys of a map.

range on strings iterates over Unicode code points. The first value is the starting byte index of the rune and the second the rune itself. See Strings and Runes for more details.

$ scala Main.scala
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111