Search code examples
scopedroolsrule-engine

Declare local rule variable using Drools


It's possible to create a local variable into a local rule definition using Drools rule engine?

I wrote an example code, but it's not compiling. This example is just to expose the idea about local declaration (I know that it's wrong)

/*...*/
    rule "Test local Variable"
        when
            String $departmentName = "Music";
        then
            System.out.println($departmentName);
    end
/*...*/

The error message is:

org.drools.CheckedDroolsException: There were errors in the rule source: [ERR 101] Line 25:2 no viable alternative at input 'String' in rule "Test local Variable"

The position [25,2] is defined by line:

String $departmentName = "Music";

Solution

  • As of Drools 5, it is not possible to declare arbitrary variables in conditions. You can bind variables to facts and attributes:

    when
       Person( $name : name )
    then
       // $name is bound to each name of each person in the working memory
    end