Search code examples
javascriptjavalambdascriptengine

Converting from string to lambda


I'm trying to use ScriptEngine to convert from a string to a lambda function for input. This is what I've come up so far, but I only experience errors:

ScripEngine engine = new ScriptEngineManager().getEngineByName("javascript");
someFunctionThatTakesInALambdaEquation((Function<Double, Double>)engine.eval("x -> x + 3")); 

Solution

  • JavaScript's syntax for a lambda expression is x => x + 3, or equivalently you can write it as an anonymous function function(x) { return x + 3; }. Take note that it is slightly different from Java's syntax for a lambda expression x -> x + 3.

    So I tried engine.eval("x => x + 3");, but got an exception from the script engine. I don't understand why.
    But with

    AbstractJSObject obj = (AbstractJSObject) engine.eval("function(x) { return x + 3; }");
    

    you can get a JavaScript function object. Then you need to convert this to a Java function object (aka lambda expression).

    Function<Double, Double> f = x -> (Double) obj.call(null, x);
    

    and then do what ever you like

    someFunctionThatTakesInALambdaExpression(f);