New(?) idea for collection literals

Typing this out from my phone so I haven’t tested the idea thoroughly but thought the idea maybe spark a good discussion.

Collection literals will only be available when there is a “CollectionBuilder” in context. For example:

fun interface ListBuilder<I, out T: List<I>> {
    operator fun buildList(varargs elements: I): T
}

This would allow code looking something like this:

    val list = with(ArrayListBuilder) {
        [1, 2, 3]
    }

Of course, Kotlin let’s us bring things into context in a lot of ways that are prettier than this, including context parameters or by implementing the interface.

As the language progresses (e.g. with truly immutable collections) more implementations of these interfaces can be added.

In this way, the notation is flexible and user-extensible. It would also always be clear (from the context) what is meant by the notation.

Sorry if this isn’t original. If it’s been discussed already, maybe someone can comment here with a link.

Here is Brian Goetz talking about something similar in an imagined Java future: https://youtu.be/Gz7Or9C0TpM?si=otGkrxApa4bFmxuX

1 Like

Tbh I actually don’t know why Kotlin doesn’t have collection literal syntax. I assume there’s a good reason for it, I just don’t know what that reason is.

At least there is a KEEP: KEEP/proposals/collection-literals.md at bobko/collection-literals · Kotlin/KEEP · GitHub

1 Like