简体   繁体   中英

Concise 2D primitive array initialization in Kotlin

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.

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: eg 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, eg:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM