本文介绍了在Kotlin中创建通用的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 假设我有一个泛型类,并且需要一个泛型类型 T 的二维数组。如果我尝试以下操作: class Matrix< T>(width:Int,height:Int){ val data :Array< Array< T>> =数组(宽度,arrayOfNulls< T>(高度))} 抛出一个错误说不能使用'T'作为实体类型参数,而是使用一个类。。解决方案 class Array2D< t>< p> (val xSize:Int,val ySize:Int,val array:Array< Array< T>>){ 伴随对象{ 内嵌操作符fun< reified T> ; invoke()= Array2D(0,0,Array(0,{emptyArray< T>()})) 嵌入式运算符fun< tified T> invoke(xWidth:Int,yWidth:Int)= Array2D(xWidth,yWidth,Array(xWidth,{arrayOfNulls< T>(yWidth)})) 内联操作符fun val array = Array(xWidth,{ val x = it Array(yWidth,{operator(x,it)})})返回Array2D(xWidth,yWidth ,数组)} } 操作符fun get(x:Int,y:Int):T {返回数组[x] [y] operator fun set(x:Int,y:Int,t:T){ array [x] [y] = t } inline fun forEach(operation:(T) - > Unit){ array.forEach {it.forEach {operation.invoke(it)}} } inline fun forEachIndexed(operation:(x:Int,y:Int,T) - > Unit){ array.forEachIndexed {x,p - > p.forEachIndexed {y,t - > operation.invoke(x,y,t)}} } } 这也允许你以类似于1d数组的方式创建2d数组,例如类似于 val array2D = Array2D< String>(5,5){x,y - > $ x $ y} 并使用索引操作符访问/设置内容: val xy = array2D [1,2] Suppose I have a generic class and I need a 2D array of generic type T. If I try the followingclass Matrix<T>(width: Int, height: Int) { val data: Array<Array<T>> = Array(width, arrayOfNulls<T>(height))}the compiler will throw an error saying "Cannot use 'T' as reified type parameter. Use a class instead.". 解决方案 Just because the syntax has moved on a bit, here's my take on it:class Array2D<T> (val xSize: Int, val ySize: Int, val array: Array<Array<T>>) { companion object { inline operator fun <reified T> invoke() = Array2D(0, 0, Array(0, { emptyArray<T>() })) inline operator fun <reified T> invoke(xWidth: Int, yWidth: Int) = Array2D(xWidth, yWidth, Array(xWidth, { arrayOfNulls<T>(yWidth) })) inline operator fun <reified T> invoke(xWidth: Int, yWidth: Int, operator: (Int, Int) -> (T)): Array2D<T> { val array = Array(xWidth, { val x = it Array(yWidth, {operator(x, it)})}) return Array2D(xWidth, yWidth, array) } } operator fun get(x: Int, y: Int): T { return array[x][y] } operator fun set(x: Int, y: Int, t: T) { array[x][y] = t } inline fun forEach(operation: (T) -> Unit) { array.forEach { it.forEach { operation.invoke(it) } } } inline fun forEachIndexed(operation: (x: Int, y: Int, T) -> Unit) { array.forEachIndexed { x, p -> p.forEachIndexed { y, t -> operation.invoke(x, y, t) } } }}This also allows you to create 2d arrays in a similar manner to 1d arrays, e.g. something likeval array2D = Array2D<String>(5, 5) { x, y -> "$x $y" }and access/set contents with the indexing operator:val xy = array2D[1, 2] 这篇关于在Kotlin中创建通用的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-01 23:19