ImmutableMap::of should accept more entries
See original GitHub issueI’m using ImmutableMap
for building structures that I can then automatically serialize to JSON, like the following adapted from http://json.org/example:
Map j = ImmutableMap.of(
"id", id,
"title", title,
"debug", "on",
"window", ImmutableMap.of(
"title", "Window title",
"name", "window_1",
"width", 500,
"height", 500
)
);
Coming from Python where JSON can be used in source code as-is, the above is a very nice alternative in Java land and I couldn’t think of a way to make it any better, syntax-wise. However, I hit the limit of the maximum 5 key-value pairs of ImmutableMap::of
, and then I had to use rather ugly workarounds (with Builder
or alternatively splitting a big Map up into two and joining them together again…).
I fully understand that there is no variable arguments overload like in ImmutableSet::of
– you couldn’t guarantee at compile-time that the number of ImmutableMap::of
arguments is even (to form key-value pairs), it would fail at run-time, and we don’t want that.
I also understand that there probably is some resistance in providing a high number of overloads. However, I still think the limit of 5 entries is too low. And resorting to Builder
is just plain ugly in some cases. I therefore propose to raise the number of overloads to 10, as this should cover most use cases and will create less headache for users. On the implementation side it is a trivial change and I don’t see any problem.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:10
- Comments:23 (15 by maintainers)
Top GitHub Comments
@jbduncan Actually, it was just a nested types in Generics that made it clumsy, it all DOES work, my bad:
Map <String, Supplier<String>> map = ImmutableMap.<String, Supplier<String>>builder() .put("one", () -> "supplier1") .build();
Having to repeat the type info is annoying but I think that’s the limitation of automatic type inference and has nothing to do with Guava.I’m not sure I understand why you consider the builder approach an ugly workaround?
ImmutableMap.builder() .put(k1, v1) .put(k2, v2) … .build()
shouldn’t be that awkward.
On Sun, Jun 7, 2015 at 6:38 AM Maik Riechert notifications@github.com wrote: