Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

guava

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.

like image 722
Gili Avatar asked Jan 30 '12 01:01

Gili


1 Answers

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.

like image 127
Louis Wasserman Avatar answered Oct 10 '22 11:10

Louis Wasserman