2

I'm trying to define a large number of primitive 2D arrays in Kotlin and it appears to lack a concise way to do so. For example, in C++ you can do the following:

int arr[2][5] =
    {{1,8,12,20,25},
     {5,9,13,24,26}};

The best I've been able to come up with in Kotlin is

val arr = arrayOf(
            intArrayOf(1,8,12,20,25),
            intArrayOf(5,9,13,24,26))

Java (with its pointless repetition) even has Kotlin beat here

int[][] arr = new int[][]
        {{1,8,12,20,25},
         {5,9,13,24,26}};

While the extra boilerplate isn't the end of the world, it is annoying.

2 Answers 2

2

As another answer points out, there's no built-in shorter syntax for this.  Your example with arrayOf() &c is the conventional solution.

(There have been proposals for collection literals in Java and Kotlin, but they're highly contentious because there are so many possibilities: e.g. would you want an ArrayList or a LinkedList or some other implementation?  Should it be mutable or immutable?  And so on.  And by the time you've added special syntax to specify that, it's longer than the existing functions!)

But if brevity is really important in your case, you could define shorter aliases for the built-in functions, e.g.:

inline fun <reified T> a(vararg e: T) = arrayOf(*e)

 

fun i(vararg e: Int) = intArrayOf(*e)

Then your example boils down to:

val arr = a(i(1, 8, 12, 20, 25),
            i(5, 9, 13, 24, 26))
Sign up to request clarification or add additional context in comments.

2 Comments

got a link to any of the proposals for Kotlin?
@lessthanoptimal: I've added some links to the answer, giving the Java Enhancement Proposal and the detailed explanation why it was shelved, along with many discussions on the Kotlin forum, and the detailed explanation of one particular Kotlin Evolution and Enhancement Process.
1

There is no shorter syntax for arrays in Kotlin, it does not provide collection literals (yet?).

val arr = arrayOf(
    intArrayOf(1,8,12,20,25),
    intArrayOf(5,9,13,24,26)
)

is the way to go.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.