Passing undefined to Nashorn Javascript in Scala / Java

I need to evaluate this function in Javascript from Scala / Java

function hello(a, b) { return a+b; } 

I made this basic code:

 val factory = new ScriptEngineManager(null) val engine = factory.getEngineByName("JavaScript") val body = """ |function hello(a, b) { | return a+b; |} """.stripMargin engine match { case engine: Invocable => engine.eval(body) println(engine.invokeFunction("hello", null, 1: java.lang.Double)) } 

For parameter a, I pass null and I get 1.0 as a result. If I crack my javascript (I SHOULD NOT DO IT) and I will do this:

 function hello(a, b) { if (a === null) { a = undefined; } return a+b; } 

I get the expected NaN.

The correct solution would be to pass undefined to invokeFunction: How do I do this?

+4
source share
1 answer

ScriptEngine.eval translates undefined to null - since Java has no concept of undefined. If you want to get the internal nashorn undefined object and pass it (why?), You can do something like this:

 import javax.script.*; public class Test { private static Object undefined; public static void main(String[] args) throws Exception { ScriptEngineManager m = new ScriptEngineManager(); ScriptEngine e = m.getEngineByName("nashorn"); e.eval("Packages.Test.setUndefined(undefined)"); e.eval("function func(a, b) { return a + b; }"); Object val = ((Invocable)e).invokeFunction("func", undefined, 44); if (val instanceof Double && ((Double)val).isNaN()) { System.out.println("got NaN as expected"); } } public static void setUndefined(Object obj) { undefined = obj; } } 
+3
source

Source: https://habr.com/ru/post/984269/


All Articles