As it was in Java, any object that is Iterable can be used in an enhanced for loop. I thought the same held true for Kotlin as well, until I discovered that kotlin.collections.Map is not Iterable at all.
from the standard library source code:
public interface Map<K, out V> {
// ....
If not, then how is something like this possible?:
val map: Map<String, Int> = HashMap()
// ...
for ((s, i) in map) {
println(s)
println(i)
// works perfectly
}
Finally, is it possibly to make custom classes that support this syntax? If so, how?
The Kotlin for loop is defined by convention:
In the case of
for(VarDecl in C) Body, the syntax form that it expands to is:as specified here in the spec.
Rather than requiring a particular interface, it is only required that overload resolution finds appropriate
operatoroverloads foriterator(),hasNext()andnext(). As an extreme example, this compiles!In your case, there exists an extension function
iteratorforMap:and
MutableMap:The
iteratormethod don't have to be declared inMap- as long as overload resolution can resolve it, the for loop works. The same applies tonextandhasNext.So to make your own class work with for loops, the minimum you need is to declare:
But I would still suggest that you implement
Iterable, because then you get all theIterableextension functions for free :)