Skip to content

Functions evaluator

Adrien LAUER edited this page Feb 23, 2017 · 1 revision

Enabling function calls

To enable function calls, you must enable the org.seedstack.coffig.evaluator.FunctionEvaluator class. This can be done when building the Coffig instance:

Coffig.builder()
      .withProviders(...)
      .withEvaluators(new FunctionEvaluator())
      .build();

or by registering an evaluator in META-INF/services/org.seedstack.coffig.spi.ConfigurationEvaluator:

org.seedstack.coffig.evaluator.FunctionEvaluator

Usage

Function calls allow to call predefined Java methods from configuration nodes. Function calls use the $fn() syntax:

symbols: [ '!', '.', '?' ]
message: $greet('World', symbols, 0)

The greet function is implemented as a method annotated with @org.seedstack.coffig.spi.ConfigFunction in a class implementing org.seedstack.coffig.spi.ConfigFunctionHolder:

package org.seedstack.samples.config;

public class GreetFunctionHolder implements ConfigFunctionHolder {
    private Coffig coffig;
    
    @Override
    public void initialize(Coffig coffig) {
        this.coffig = coffig;
    }

    @ConfigFunction
    private String greet(String name, String[] symbols, int index) {
        return String.format("Hello %s %s", name, symbols[index]);
    }
}

The GreetFunctionHolder class must be registered with the Java ServiceLoader mechanism, with the following file:

src/main/resources
    └ META-INF
        └ services
            └ org.seedstack.coffig.spi.ConfigFunctionHolder

containing:

org.seedstack.samples.config.GreetFunctionHolder

Evaluation

In the example above, the node message will be evaluated to "Hello World!". Parameters are automatically mapped to their Java type, allowing to pass complex objects to configuration functions. String literals can be passed as parameters by enclosing them with single quotes. Parameters that reference other nodes must specify their full path.

Escaping

Function calls can be avoided by escaping the dollar sign with a backslash: \$greet('World', symbols, 0) will be evaluated to "$greet('World', symbols, 0)".

Nesting

Parameters can be other functions calls: $greet('World', $getSymbols(), 0) will use the return value of the getSymbols() function call as second parameter.