0

I want to have a 2x2 2d array of int in kotlin but the indexing should be using booleans like this:

      | true | false |
----------------------
true  |  0   |  75   |
----------------------
false |  1   |  34   |

I know I can use a 2d array of int but not sure how to represent the indexing via booleans.

Any help much appreciated

Jofbr
  • 455
  • 3
  • 23

1 Answers1

0

I don't think this is a good idea in general, but Kotlin does allow this kind of operator overloading (Array<IntArray> is the Kotlin type for 2d array of ints):

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]
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • can you make this a function so it uses {} not = – Jofbr May 21 '18 at 07:41
  • and is it possible to make this generic so the 2d array can be of ints or double? – Jofbr May 21 '18 at 07:41
  • You have to copy the code with `DoubleArray` instead of `IntArray` (and other types if you need them). `Array>` is the generic option, but it has overhead: it ends up represented as a 2d array of `Object`s. See https://kotlinlang.org/docs/reference/basic-types.html. – Alexey Romanov May 21 '18 at 07:57