简体   繁体   English

Kotlin中的简洁2D基本数组初始化

[英]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. 我正在尝试在Kotlin中定义大量的原始2D数组,但似乎缺少一种简洁的方法。 For example, in C++ you can do the following: 例如,在C ++中,您可以执行以下操作:

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 我在Kotlin能够想到的最好的方法是

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 Java(无意义的重复)甚至在这里击败了Kotlin

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. 您使用arrayOf() &c的示例是常规解决方案。

(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!) (已经提出了使用JavaKotlin的集合文字的建议,但由于存在多种可能性,它们具有很高的 争议性 :例如,您是否想要ArrayList或LinkedList或其他实现?它是可变的还是不可变的?等等) 。并且当您添加特殊语法来指定它时,它比现有函数更长!)

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?). 在Kotlin中,数组没有更短的语法,它不提供集合文字(还可以吗?)。

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

is the way to go. 是要走的路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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