Skip to content

Do we have Iterators in Ballerina? #31135

Answered by MaryamZi
Asitha asked this question in Q&A
Discussion options

You must be logged in to vote

Yes. An object can make itself iterable by using type inclusion with object:Iterable (i.e., subtype of Iterable<T,C>) and defining an iterator method that returns an iterator object (i.e., subtype of Iterator<T,C>).

import ballerina/io;

class Store {
    *object:Iterable;

    Configuration[] arr = [];

    public function iterator() returns 
            object { public function next() returns 
                                record {| record {| int id; anydata value; |} value; |}?; } {
        return new EnabledConfigIterator(self.arr);
    }
}

public class EnabledConfigIterator { 
    private record {| int id; anydata value; |}[] details;
    private int index = 0;

    function init(C…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Asitha
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants