Reputation: 1439
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)
}
Upvotes: 0
Views: 81
Reputation: 57124
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-functioniterator()
, whose return type
has a member- or extension-functionnext()
, and
has a member- or extension-functionhasNext()
that returnsBoolean
.
All of these three functions need to be marked asoperator
.
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 theMap
.
Upvotes: 3