Search code examples
droolsdslrules

Drools: using the same DSL definition twice with a variable throws a duplicate variable error


If you define a DSL file with some lines, and one of them uses a variable, you cannot use it twice in a rule because you will get a duplicate variable error.

What's the best way to avoid this? Ideally I would like to avoid to create two copies of the DSL line to just change the variable name.

ie, the DSL line:

[when][]For all qualifications of type Higher=$highers: Higher()

this cannot be used twice in the same rule or we get a duplicate $highers variable.


Solution

  • You can synthesize the name of a binding variable like any other chunk of text:

    [when][]there is a qualification of type {qualification}=
          ${qualification}: {qualification}()
    

    But it's going to be tricky because you'll have to make references to this variable variable variable, too:

    [then] print {qualification}=System.out.println( ${qualification} );
    

    instead of the straightforward

    [then] print qualification=System.out.println( $qualification );
    

    A lurking danger is that the amount of text that remains as a "landmark" around the macro variables is reduced which may result in multiple matches.