Gili
Gili

Reputation: 90033

Why doesn't ImmutableMap.builder().build() pick the correct type parameters?

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.

Upvotes: 13

Views: 4435

Answers (2)

y2k-shubham
y2k-shubham

Reputation: 11607

Courtesy: @GauravGoel

Use syntax ImmutableMap.<TypeA, TypeB>builder() to 'seed' the builder with correct types.


Working example

Suppose you have

final Map<String, Object> mapA = {..};
final Map<String, Object> mapB = {..};

And you want to 'merge' them using ImmutableMap.builder, you can do the following to overcome that type-inferencing problem

final Map<String, Object> mapABmerged = ImmutableMap.<String, Object>builder()
   .putAll(mapA)
   .putAll(mapB)
   .build();

That peculiar syntax ImmutableMap.<String, Object>builder() is quite unconventional and therefore difficult to come up with

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198123

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.

Upvotes: 22

Related Questions