Shorthand for Collection Construction

It will be very awesome to have shorthand to construct a collection.

// current method
val views = listOf(binding.singleText , binding.marriedText , binding.divorcedText)

// requested method:
val views = (binding.singleText , binding.marriedText , binding.divorcedText)

i do this very often - interaction with all similar types at once with map or forEach.
now i realy wish we have this shorthand for collection constructor… somehow listOf is not short enough for me. I like how old style use to construct array or such, only with [...] it is awesome, i miss it so much.

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…)


My 2c on the matter:

Use square bracket syntax, that’s pretty standard. Always create Lists, not MutableLists, or Sets, or anything else. Support Maps via square bracket syntax of Pairs, same as current mapOf() syntax.

For example, List:

val myList = [1, 2, 3]

val myMap = [1 to "1", 2 to "2", 3 to "3"]

Personally, I’d really like colon syntax for Maps, like Groovy has:

val myMap = [1:"1", 2:"2", 3:"3"]

But I’m assuming there’s a reason Kotlin uses the to infix function rather than something like a colon.

listOf() is not that verbose, no, but it is a bit extra, and same with having to use to to create Maps. :slight_smile: It’s a nice to have that’d make creating collections a bit nicer.

1 Like