I am using Immutables Java library, how can I enforce a specific map implementation, without having to use a specific reference?
@Immutable
public interface ConfigIF {
Map<String, String> getOptions();
}
If I use the above code the concrete Map
is a LinkedHashMap
.
@Immutable
public interface ConfigIF {
TreeMap<String, String> getOptions();
}
If I use the above code both the reference and the implementations are TreeMap
.
Is there a way to specify Map
as a reference but enforce TreeMap
as concrete type?
Absolutely not - and it should be forbidden (that is : no option given to you as a user to alter that). This is not specific to your library, but any code in general that returns a Map
instead of TreeMap
let' say.
Look it the other way, if you return a Map
users are not expect to call ceilingEntry
on it (that is available in TreeMap
, but not in Map
) via cast of the reference.
java-8 does the same thing when via it's Collectors.toXXX
. For example Collectors.toList
explicitly says:
There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned.
This means that they are allowed to return whatever they find the most appropriate.