groovy: convert a list of interface implementation to a map with compileStatic

196 Views Asked by At

I am just a newer to groovy.

@Service
@CompileStatic
@Slf4j
class JourneyExecutionService {

    @Autowired
    List<DecisionEngineService> engineList;

    Map<String, DecisionEngineService> engineMap;
    void init(){
        engineMap = engineList.collectEntries {[it.getIndex(), it]}
        engineMap = engineList.stream().collect(Collectors.toMap(DecisionEngineService.getIndex, Functions.identity()))
    }

The compile shows both statements in the init function fail due to the error:

Cannot assign 'Map<Object, Object>' to 'List<String, DecisionEngineService>' and Cannot resolve symbol 'getIndex'

The 2nd statement in a java stream style.

The interface interface is like

interface DecisionEngineService {

    String getIndex()
}

Can anyone helps fix the compileation issue? Thanks

1

There are 1 best solutions below

0
On

It should be enough to cast the map explicitly:

Map<String, DecisionEngineService> engineMap;

void init(){
  engineMap = (Map<String, DecisionEngineService>)engineList.collectEntries {[it.index, it]}
}