With medini 2024 R2 the Java Script engine version was increased and with that a script can now use arrow functions. The name is derived from the operator which is ``=>`` which looks like an arrow. There is pretty good explanation out there in the net for example at JavaScript Arrow Function.
This article is not really about the arrow function itself and its advantages but more on how we can use them together with known scripting API as the ``Finder`` resp. ``FinderResult``. Lets take this example:
finder.findByType(Metamodel.projectmodel.PJPackage).filter(function(p) {
return p && p.containedElements.size() > 0;
});
This example finds all packages which have content. According to the "Arrow Function" articles, one would now be able to change that into:
finder.findByType(Metamodel.projectmodel.PJPackage).filter(p => p && p.containedElements.size() > 0);
However, that fails with an error: Cannot convert org.mozilla.javascript.ArrowFunction to de.ikv.medini.scripting.core.Filter which pretty much explains the problem. The scripting API is a Java API and accepts a simple function with a single parameter. The Arrow Function is internally converted into a complex function interface with lots of parameters like scripting context etc. The tight coupling of Java and Rhino scripting is suddenly an issue here (for first time) and blocks us which is a pity.
We can now try to workaround the problem a bit like this:
finder.findByType(Metamodel.projectmodel.PJPackage).toArray().filter(p => p && p.containedElements.size() > 0);
That solution is pretty nice. We convert the finder result first to a native JS array and can use the filter function of that array. Only problem here is that we somewhat lose the Finder API, no more "and" or "not" or "withTag" calls possible. That brings us to this solution:
finder.findByType(Metamodel.projectmodel.PJPackage).filter( {accept: p => p && p.containedElements.size() > 0} );
Which works! But wait, what is happening here? The enclosing bracelets convert the construct into an object with a single function "accept" which internally can be mapped by Rhino to a "filter function" which is accepted by the filter function. The magic that the filter is calling the filter function which evaluates the arrow function is in Rhino :-)
Happy Arrow
Jan