Is there a way to direectly loop over a Java Iterable in Kawa or alternatively loop on the java.util.Iterator

185 views Asked by At

I have not found the way to directly loop over a Java java.lang.Iterable or java.util.Iterator in Kawa (Scheme) using Java interop

I can get at my Java java.lang.Iterable and then at my java.util.Iterator and loop over the items using a recursive named let:

((define blkaccessor::java.lang.Iterable (bfaccessor:getHeaderAccessor))
(define blkaccitr::java.util.Iterator (blkaccessor:iterator))
(let        loop    ((block-item::JDataBlockItemData (blkaccitr:next)))
             (when (blkaccitr:hasNext)
                (display &{&[block-item:name] = &[block-item:value]
})
                (loop (blkaccitr:next))
            )
)

The code runs and lists all items in the REPL but there must be a way to directly loop on the Iterable or Iterator.

NOTE: I just realized that my recursive "let" is terribly wrong (it will fail if the iterator hasNext method returns false on entry because I initialize block-item by calling next without checking hasNext first and it will not print all items) but this part of the code is not essential to answering the question and it could be fixed (I am running out of time right now but I will try to update the code tomorrow).
The starting point and essential code are the first two lines where I get my Iterable and then my Iterator.

1

There are 1 answers

1
coredump On BEST ANSWER

It looks like "map" and "for-each" should be able to iterate over iterators: https://gitlab.com/kashell/Kawa/commit/9428041dca2d262edc3a5ab781e1302f33e279a1

Your code cannot be reproduced without more details (or less) but the following is an example of iteration over a Java array of strings:

(let ((java-string-array (String[] "aaa" "bb" "c")))
  (for-each (lambda (string) (write string))
            java-string-array))