yf0994 / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Add methods to ImmutableMap to improve generic inferencing. #1166

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Consider the following:-

ImmutableMap<String, String> map = ImmutableMap.builder().put("foo", 
"bar").build();

This doesn't compile because the compiler is unable to infer the generic type 
of the map which is rather irritating as you end up having to write this noise

ImmutableMap<String, String> map = ImmutableMap.<String, 
String>builder().put("foo", "bar").build();

I believe this could be fixed by adding a method like

public static <K, V> Builder<K, V> builder(K key, V value) {
  return ImmutableMap.<K, V>builder().put(key, value);
}

so a client could then write things much more concisely:-

ImmutableMap<String, String> map = ImmutableMap.builder("foo", "bar").build();

It would be nice to call this method 'put' but that would duplicate the other 
put method.

Original issue reported on code.google.com by MrChrisP...@googlemail.com on 12 Oct 2012 at 9:46

GoogleCodeExporter commented 9 years ago
I like that. And of course there should be similar factory methods for all the 
ImmutableCollection+ builders.

Original comment by SeanPFl...@googlemail.com on 12 Oct 2012 at 10:05

GoogleCodeExporter commented 9 years ago
A few years back, we had a long discussion about this. We are not a fan of 
having to write "new ImmutableMap.Builder<String, String>," so we liked the 
idea of builder(K, V) to stamp it out. In the end, though, we couldn't 
ourselves that it was worth making it more marginally difficult to read and 
modify existing code:

.builder("a", "b")
.put("c", "d")
.put("e", "f")

First, it looks a little ragged. Second, removing the first line now requires 
changes to two lines:

.builder("c", "d")
.put("e", "f")

We're not certain that we made the right choice, but I think we've spent enough 
on the discussion that we've put this to bed.

Maybe, though, we should be looking to increase the number of "fake varargs" 
supported by ImmutableMap.of()?

Original comment by cpov...@google.com on 12 Oct 2012 at 3:59

GoogleCodeExporter commented 9 years ago

Original comment by wasserman.louis on 12 Oct 2012 at 4:06