title: Instantiating generic array in Kotlin
body: <p>Why this doesn't compile? I get compile error in 3 line</p>
  
  <blockquote>
    <p>Cannot use T as reified type parameter. Use class instead</p>
  </blockquote>
  
  <pre><code>class Matrix2d&lt;T&gt;(val rows: Int, val cols: Int, init: (Int, Int) -&gt; T) {
  
     var data = Array(rows * cols, { i -&gt;
        val r = Math.floor(i.toDouble() / cols).toInt()
        init(r, i - r * cols)
     })
  
     operator fun get(row: Int, col: Int): T = data[row * cols + col]
  
     operator fun set(row: Int, col: Int, v: T) = {
        data[row * cols + col] = v
     }
  }
  </code></pre>
  
  <p><strong>Solution</strong></p>
  
  <p>I added a factory function which looks like a second constructor but implemented in inline function</p>
  
  <pre><code>class Matrix2d&lt;T&gt;(val rows: Int, val cols: Int, private val data: Array&lt;T&gt;) {
  
     companion object {
        operator inline fun &lt;reified T&gt; invoke(rows: Int, cols: Int, init: (Int, Int) -&gt; T): Matrix2d&lt;T&gt; {
           return Matrix2d(rows, cols, Array(rows * cols, { i -&gt;
              val r = Math.floor(i.toDouble() / cols).toInt()
              init(r, i - r * cols)
           }))
        }
     }
  
     init {
        if (rows * cols != data.size) throw IllegalArgumentException("Illegal array size: ${data.size}")
     }
  
     operator fun get(row: Int, col: Int): T = data[row * cols + col]
  
     operator fun set(row: Int, col: Int, v: T) {
        data[row * cols + col] = v
     }
  }
  </code></pre>