O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. First, we get an instance of ScriptEngine with the ES6 language features enabled:
        NashornScriptEngineFactory factory =                new NashornScriptEngineFactory();        ScriptEngine engine = factory.getScriptEngine("--language=es6");
  1. Let's define a JavaScript function to find the sum of two numbers:
        engine.eval("function sum(a, b) { return a + b; }");
  1. Let's invoke the function defined in the previous step:
        System.out.println(engine.eval("sum(1, 2);"));
  1. Then we will look at the template string support:
        engine.eval("let name = 'Sanaulla'");        System.out.println(engine.eval("print(`Hello Mr. ${name}`)"));
  1. We will use the new Set construct in ES6 and the new for loop to print the Set elements:
        engine.eval("var s = new Set(); s.add(1).add(2).add(3).add(4).add(5).add(6);"); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required