Search code examples
scalagenericsoptaplanner

Calling a Java method with unknown type and passing the result in another Java method from Scala doesn't compile


I'm playing with Optaplanner in Scala and I'm calling the "groupBy" method like this:

    factory
      .forEach(classOf[ClassA])
      .filter(classA => classA.classB != null)
      .groupBy((classA: ClassA) => classA.classB)
      ....

This works. However, if I try to add the count() constraint collector like this:

    factory
      .forEach(classOf[ClassA])
      .filter(classA => classA.classB != null)
      .groupBy((classA: ClassA) => classA.classB, count())
      ....

it complains with "Cannot resolve overloaded method 'groupBy'".

I have tried passing explicitly the generic type:

    factory
      .forEach(classOf[ClassA])
      .filter(classA => classA.classB != null)
      .groupBy((classA: ClassA) => classA.classB, count[ClassB]())
      ....

The count() constraint collector parameter has type UniConstraintCollector[ClassB, _, Integer]

Whereas the groupBy method has signature:

<GroupKey_, ResultContainer_, Result_> BiConstraintStream<GroupKey_, Result_> groupBy(
            Function<A, GroupKey_> groupKeyMapping,
            UniConstraintCollector<A, ResultContainer_, Result_> collector)

But it doesn't change the outcome.

Any idea what's wrong here?


Solution

  • According to the signature, both function arguments of groupBy should map from the same A but you're trying to apply it to the 1st function mapping from ClassA and the 2nd function mapping from ClassB.

    The following compiles:

    .groupBy((classA: ClassA) => classA.classB, count[ClassA]())
    

    Do you want the following?

    .groupBy((classA: ClassA) => classA.classB)
    .groupBy(count[ClassB]())