Contains array of arrays

In fact the first statement is false for a bad reason.

itemA in items

means in fact :

items.contains(itemA)

If you read the code of Collection.contains() you will see that contains use the equals() comparison (== in kotlin). But array equality in java and kotlin is reference equality.

You have to solutions : the first one is to use list instead of array, because it’s override the equals() comparison, the second one is to define an infix function like :

infix fun <T> Array<T>.isIn(array: Array<Array<T>>): Boolean {
    return array.any { it.contentEquals(this) }
}

val itemA = arrayOf(0,0)
val itemB = arrayOf(1,1)
val items = arrayOf(arrayOf(1,1), arrayOf(2,2), arrayOf(3,3))
assertFalse(itemA isIn items)
assertTrue(itemB isIn items)
1 Like