Search code examples
loopsfor-loopkotliniterator

How is a for loop possible while using a Map?


AFAIK a Map doesn't declare that it implements Iterable (in contrast to Collection which does). So how is it possible to run over all map entries using a for loop? Code:

val map = mutableMapOf<String,Int>("One" to 1, "Two" to 2, "Three" to 3, "Four" to 4)
for (element in map)
{
        println(element.value)
}

Solution

  • Implementing Iterable isn't the requirement to be iterable but instead https://kotlinlang.org/docs/reference/control-flow.html#for-loops states

    for iterates through anything that provides an iterator, i.e.
    has a member- or extension-function iterator(), whose return type
    has a member- or extension-function next(), and
    has a member- or extension-function hasNext() that returns Boolean.
    All of these three functions need to be marked as operator.

    and https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/ actually has a iterator() that fits those requirements

    Returns an Iterator over the entries in the Map.