Create array as [1, 2, 3] and maps as { a: 10 }

Just wondering if there’re any plans to introduce a human way to create collections? Something like [1, 2, 3] and maps as { a: 10 }.

I believe the reason they weren’t introduced originally, because it was not clear how to do it in a proper way.

Kotlin development started 11 years ago, in 2010. How many more years kotlin dev team needs to solve this immensely complicated challenge?

It is called collection literals, and you should probably watch this video for discussion.

Personally, I do not see how [1,2,3] is be better than List(1,2,3). When I just started to work in kotlin (after groovy), I was advocating for collection literals, but after four years, I changed my perspective and now I do not see any viable reasons to introduce them.

4 Likes

By saying [1, 2, 3] which one do you mean exactly?

listOf(1, 2, 3)
mutableListOf(1, 2, 3)
arrayOf(1, 2, 3)
arrayListOf(1, 2, 3)

I think current solution is better, because it is explicit what kind of data structure we need to create.

5 Likes

By saying [1, 2, 3] which one do you mean exactly?

Possible solutions could be

  1. infer type val list: List<Int> = [1, 2, 3]
  2. For val list = [1, 2] collect usage stats over top 100 kotlin projects on github and see what’s used the most frequently. If you want something else do val list = [1, 2, 3].toMutableList() or use old way val list = mutableListOf(1, 2, 3).

The thing is - you lose nothing, if you wish you can just ignore this literal syntax and continue to use whateverOf(1, 2, 3). But people who like this syntax could use it.

My personal opinion is that the current solution is better than both of your suggestions. But as I said, this is just an opinion.

Anyway, the case here is not that this feature is missing, but it was designed in a different way than you expect.

Also, it seems this is actually planned for future versions of Kotlin. It is/was discussed here and here. It takes years already for arguing on what would be the best design for this proposal :wink:

2 Likes

The current collection literal proposal makes sense in conjunction with the tuple builders proposal, but not as a stand-alone feature.

3 Likes