Proposal: Collection Literals

Joshua Bloch jjb at google.com
Tue Mar 31 01:13:42 PDT 2009


Mark,
Thanks for reading the proposal. Inferring the right side from the left is
called "target typing," and with one small exception, Java doesn't do it.
 My proposal uses existing type inference rules, and allows you to use
collection literals in in any reasonable context.  Besides the right hand
side of assignments, this includes use as a method or constructor parameter
(e.g., new HashSet({"Larry", "Moe", "Curly"}), before a dot (e.g., [3, 1, 4,
1, 5, 9, 2, 6, 5, 3, 5, 9].size()), and elsewhere.  We don't have to further
complicate Java's already complicated type inference logic to make this
work; instead, we take advantage of the rules that are already there.

                   Josh

On Tue, Mar 31, 2009 at 12:56 AM, Mark Thornton <mthornton at optrak.co.uk>wrote:

> Joshua Bloch wrote:
>
>> The method invocations (Collections.unmodifiableList(Arrays.asList) are
>> just
>> noise. With list literals, it would look like this:
>>
>>    final List<Integer> piDigits = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9];
>>
>>
>> By substituting curly braces for the square brackets, you get a set
>> literal
>> in place of a list:
>>
>>
>>    final Set<Integer> primes = { 2, 7, 31, 127, 8191, 131071, 524287 };
>>
>>
> Would it be possible to infer the type of the RHS from the left (and thus
> also avoid Neal's issue with generics). You could then use {} for both lists
> and sets, and not need the odd syntax for an empty map.
>
> Thus:
>
> List<Integer> emptyList = {};
> Set<Integer> emptySet = {};
> Map<String, String> emptyMap = {};
>
> Regards,
> Mark Thornton
>
>



More information about the coin-dev mailing list