Why does Map<String, ?> test = ImmutableMap.builder().build();
fail to compile, but Map<String, ?> test = ImmutableMap.<String, Object>builder().build();
work fine?
The first code sniplet fails with:
error: incompatible types
Map<String, ?> test = ImmutableMap.builder().build();
^
required: Map<String,?>
found: ImmutableMap<Object,Object>
I believe the Guava committers meant for this to work.
This is not a failure in Guava, but rather in the way Java resolves generics, and it's something we can't control. =(
Believe us: this is something that we spent a lot of time on. In this issue, Kevin mentions that we attempted no less than fifteen approaches for trying to get it so that you didn't have to explicitly specify these type parameters.
If you're only interested in the case of ImmutableMap.builder().build()
, that is, with no entries in the map...then you should be using ImmutableMap.of()
. That won't have any funny issues with generics: it'll just work.