Warum kompiliert das nicht? Ich bekomme Kompilierungsfehler in 3 ZeileGenerisches Array in Kotlin instanziieren
Kann nicht T als verdingter Typ Parameter verwenden. Verwenden Klasse statt
class Matrix2d<T>(val rows: Int, val cols: Int, init: (Int, Int) -> T) {
var data = Array(rows * cols, { i ->
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
}
}
Lösung
Ich habe eine Fabrik-Funktion, die wie eine zweite Konstruktor sieht aber
class Matrix2d<T>(val rows: Int, val cols: Int, private val data: Array<T>) {
companion object {
operator inline fun <reified T> invoke(rows: Int, cols: Int, init: (Int, Int) -> T): Matrix2d<T> {
return Matrix2d(rows, cols, Array(rows * cols, { i ->
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
}
}
Mögliches Duplikat [Kotlin NDArray mit einem Lambda-Konstruktor mit allgemeinem Rückgabetyp] (http://stackoverflow.com/questions/35581867/kotlin-ndarray-with-a-lambda-constructor-with-generic- Rückgabetyp) – mfulton26