Expressions in Painless DSL

Hi,

Does Painless support immediately-invoked function expressions (IIFEs)? For reasons (I'd prefer not to explain them) I need to return the result of several expressions to an if-statement, as shown in an example below.

if ( (function () { def x = false; return !x; })() ) {
  // -- do something.
}

I haven't found a way to get IIFE's working in Painless, are they supported?

Just to clarify, I can't write

boolean someFn () {
  def x = false;
  return !x;
}

def condition = someFn();

if (condition) {
  // -- do something
}

in this case, I need to use an IIFE.

Thanks for reading,

I don't believe Painless supports this directly, but you can fake it by creating a method that takes a BooleanSupplier (or whatever other functional interface you need) and just returns the result:

POST _scripts/painless/_execute
{
  "script": {
    "source": """
    boolean exec(BooleanSupplier sup) {
      return sup.getAsBoolean();
    }
    if(exec(() -> {boolean x = params.val;return !x;})) {
      return "Fake IIFEs!"
    }
    """,
    "params": {
      "val": false
    }
  }
}

Which returns:

{
  "result" : "Fake IIFEs!"
}

Does that work for you?

Thanks, that works perfectly!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.