Search code examples
arrayskotlinbooleankotlin-extension

Kotlin represent array with boolean indexing


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


Solution

  • 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]