UnmodifiableMap with Function<X, Y> values fails to compile

389 views Asked by At

I have a reference:

public final static LinkedHashMap<String, Function<OrderBean, String>> DELEGATES;

Which I initialize like:

static {
    LinkedHashMap<String, Function<OrderBean, String>> tmp = new LinkedHashMap<>();
    tmp.put(OrderCols.FIELD1, OrderBean::getFIELD1);
    tmp.put(OrderCols.FIELD2, OrderBean::getFIELD2);
    ...        
    DELEGATES = Collections.unmodifiableMap(tmp);
}

On the last line of the static block (the assignment to DELEGATES), I get this compiler error:

Error:(64, 48) java: incompatible types: no instance(s) of type variable(s) K,V exist so that java.util.Map conforms to java.util.LinkedHashMap>

Am I messing something up? Or do unmodifiable views don't like Function types?

1

There are 1 answers

6
Louis Wasserman On BEST ANSWER

No, your issue is that instead of

public final static LinkedHashMap<String, Function<OrderBean, String>> DELEGATES;

you should have

public final static Map<String, Function<OrderBean, String>> DELEGATES;

...because unmodifiableMap returns a bare Map implementation. (The backing data structure will still be a LinkedHashMap, though.)