Initializing a 2D (multi-dimensional) array in Scala

后端 未结 6 1456
深忆病人
深忆病人 2020-12-24 02:13

It\'s easy to initialize a 2D array (or, in fact, any multidimensional array) in Java by putting something like that:

int[][] x = new int[][] {
        { 3,          


        
6条回答
  •  温柔的废话
    2020-12-24 02:55

    Since I'm also in disgust with this trailing comma issue (i.e. I cannot simply exchange the last line with any other) I sometimes use either a fluent API or the constructor syntax trick to get the syntax I like. An example using the constructor syntax would be:

    trait Matrix {
      // ... and the beast
      private val buffer = ArrayBuffer[Array[Int]]()
      def >(vals: Int*) = buffer += vals.toArray
      def build: Array[Array[Int]] = buffer.toArray
    }
    

    Which allows:

    // beauty ... 
    val m = new Matrix {
      >(1, 2, 3)
      >(4, 5, 6)
      >(7, 8, 9)
    } build
    

    Unfortunately, this relies on mutable data although it is only used temporarily during the construction. In cases where I want maximal beauty for the construction syntax I would prefer this solution.

    In case build is too long/verbose you might want to replace it by an empty apply function.

提交回复
热议问题