Shorthand for Collection Construction

What sort of collection do you want to construct?

A mutable one, or an immutable one? A List, or a Set, or simply a plain Collection? Map types too? Does it need to be concurrent? What element type should it have? (You can’t necessarily infer the element type from the arguments; there might not be any arguments, and even if there were, you might want a supertype, e.g. to ensure it’s nullable.) What sort of performance should it have? (E.g. how should it trade off memory for speed? Should it be optimised for small collections, or to improve the worst case?)

There’s no single right answer to all those questions — so you’d either have to make a single choice that doesn’t work for some cases, or you’d have to support some options (which would mean its syntax wouldn’t be significantly shorter than the existing 6-character listOf).

This idea has been discussed many times before, but although it’s attractive, there’s not been any consensus about how to do it with enough benefit to justify the extra complexity it would bring to the language.

(Note that many of the languages that do have collection literals lack Kotlin’s flexibility with collection types, and so aren’t really comparable. Also, I suspect the simple paren syntax you suggest would either have to be restricted to immediately after =, which would prevent lots of desirable usages, or it would conflict with existing uses of parens for grouping etc.)

And listOf() isn’t that verbose, is it? (I remember the old days, in Java ≤ 7, when you’d need a whole block of code to create an ArrayList, call add() for each item, and then use the result…)

4 Likes