Well, actually I have asked myself that questin a few times, simply because the java.util.List interface offers a forEach function with a similar signature as JS. Any way it does not work in medini JS and never did.
Now with 2024 R2 we have upgraded the Rhino engine version and I had the hope that this has improved so I had a closer look at it and would like to share my findings.
So basically this is how we did it in the past, we simply converted the List to an Array. Now with the new Rhino we can use the "Arrow Function":
var scope = finder.project;
var list = scope.nestedPackages;
function log(p) {
console.log(p.name);
}
// works now with arrow function
list.toArray().forEach(p => log(p));
Works nicely now lets try to apply this to the List directly:
var scope = finder.project;
var list = scope.nestedPackages;
function log(p) {
console.log(p.name);
}
// still does not work for Collections
list.forEach(p => log(p));
This results in "Cannot convert [...] ArrowFunction to [...] Consumer". So we probabaly hit a problem with the new => style. Hm, next I tried to go back to classic inline function:
var scope = finder.project;
var list = scope.nestedPackages;
function log(p) {
console.log(p.name);
}
// even this does not work
list.forEach(log);
Not working nut gives a different error: "Cannot convert function to interface [...] Consumer since it contains methods with different names. Aha, that gave the final hint: java.util.Consumer has an "andThen" fucntino since a while with a default implementation. Rhino doe snot like that. Anyway, with this little wrapper it finally worked:
var scope = finder.project;
var list = scope.nestedPackages;
function log(p) {
console.log(p.name);
}
// the trick
function toConsumer(f) {
return {
accept: f,
andThen: function(after) {
throw "not implemented";
}
};
}
// works!
list.forEach(toConsumer(log));
So bottom line is that List.forEach is still not the same as Array.forEach but with a little trick we come closer.
Happy Scripting
Jan