Kotlin 用布尔索引表示数组
Kotlin represent array with boolean indexing
我想在 kotlin 中有一个 2x2 二维 int 数组,但索引应该使用这样的布尔值:
| true | false |
----------------------
true | 0 | 75 |
----------------------
false | 1 | 34 |
我知道我可以使用 int 的二维数组,但不确定如何通过布尔值表示索引。
非常感谢任何帮助
总的来说,我认为这不是个好主意,但 Kotlin 确实如此 allow this kind of operator overloading(Array<IntArray>
是二维整数数组的 Kotlin 类型):
operator fun Array<IntArray>.get(x: Boolean, y: Boolean) = this[if (x) 1 else 0][if (y) 1 else 0]
val array: Array<IntArray> = ....
array[true, false]
我想在 kotlin 中有一个 2x2 二维 int 数组,但索引应该使用这样的布尔值:
| true | false |
----------------------
true | 0 | 75 |
----------------------
false | 1 | 34 |
我知道我可以使用 int 的二维数组,但不确定如何通过布尔值表示索引。
非常感谢任何帮助
总的来说,我认为这不是个好主意,但 Kotlin 确实如此 allow this kind of operator overloading(Array<IntArray>
是二维整数数组的 Kotlin 类型):
operator fun Array<IntArray>.get(x: Boolean, y: Boolean) = this[if (x) 1 else 0][if (y) 1 else 0]
val array: Array<IntArray> = ....
array[true, false]