miguelsuri
miguelsuri

Reputation: 1

Drools getting a List() object from a declared variable problem

I have this rule that for some reason does not execute even though logically it should:

rule "Getting a List from a declared variable"
  when
    $object_with_var = Foo()
    $class_var: List() from $object_with_var.getListVar()
  then
    print("Rule fired!")
end

And the object that I insert into the KieSession:

class Foo() {
  @Getter
  List() listVar;

  public void addToListVar(Object something) {
      if (this.listVar == null) {
          this.listVar = new ArrayList<>();
      }
      this.listVar.add(something);
  }
}

When I execute the rule I make sure to instantiate Foo and add the correct information to the list so it is not null and not empty. The Foo object is then added to the KieSession. When I match just for Foo in the rule such that:

...
when
    $object_with_var = Foo()
then
...

The rule does execute. But for some reason simply getting/declaring the List variable seems to give problems:

...
when
    $object_with_var = Foo()
    $class_var: List() from $object_with_var.getListVar()
then
...
rule ""
  when
    Foo(listVar != null , !listVar.isEmpty())
  then
    ...something...
end

But I want to understand why declaring the variable doesn't work.

Upvotes: -1

Views: 32

Answers (1)

Roddy of the Frozen Peas
Roddy of the Frozen Peas

Reputation: 15219

I have this rule that for some reason does not execute even though logically it should:

rule "Getting a List from a declared variable"
 when
   $object_with_var = Foo()
   $class_var: List() from $object_with_var.getListVar()
 then
   print("Rule fired!")
end

Logically, this rule should not execute because you have a syntax error.

To assign the Foo in working memory to $object_with_var, you use a colon not an equals sign:

$object_with_var: Foo()

So your LHS would be:

$object_with_var: Foo()
$class_var: List() from $object_with_var.getListVar()

I have seen occasional issues with using List() from where the compiler complains about instantiating an interface. If that happens, you can use ArrayList() from instead. (Sometimes happens with List/ArrayList and Map/HashMap. Never could figure out why, but the workaround is simple enough.)

Eg this would be the workaround if you get the error about instantiating interfaces:

$myFoo: Foo()
$myList: ArrayList() from $myFoo.getListVar()

Upvotes: 0

Related Questions