Experiments with Kotlin Array Literals

Alexander Kosenkov
Jun 21, 2017 · 3 min read

The community has voted on the most demanded feature in Kotlin:

An the winner is… Collection literals!

It looks like programmers want to paste some JSON literals in their code:

Let’s see what can be done already today.

Lists or Arrays?

Obviously,

looks better than

but what should be the implicit type? Array, List of Ints, YourMatrix, PersistentVector or any of Guava collections? Unfortunately, compiler cannot decide for us: Unsupported [Collection literals outside of annotations], which the only reasonable thing to do.

There must always be two aspects of such syntax:

  1. Explicit: tell the compiler what exactly do you mean by [ a ].
  2. Implicit: once the choice is made, you can use that agreement.

Explicit decision might hard-coded in the compiler and documented, but it is a terrible idea, obviously.

I can imagine some half-acceptable ways:

  • choice by the receiver variable type:
    val array: IntArray = [1, 2, 3]
    - actually, this is already implemented for Annotations
  • using annotations on the function and some black magic:
    @ImplicitArrays fun test() { val magic = [1, 2, 3] }
  • defined by the import on top of the file

But there is a better way…

Abuse the `operator fun get` for vectors!

Square brackets are already supported in the language:

The only caveat is that right now you must write this or any other object:
val implicit = this [3, 4, 5]
but Andrey Breslav might remove that limitation: this is already implicit pretty much everywhere, so why not for local operator fun get?

Alternatives to the member function exist as well:

  • Extend a class or an interface where get is already defined
  • Directly import a specific get function
  • Use Type-Safe Builders, which provide the context for the get operator

Which Map implementation to choose?

Type-Safe Builders to the rescue!

My closest match so far is:

… to be continued


Please feel free to share and comment on the post or specific decisions here. I’d love to hear your feedback!