Search code examples
arrayskotlinequalitykotlin-experimental

UByteArray equality operator


In Kotlin code I have two UByteArray objects, and I want to know if they have the same stuff in them:

val a : UByteArray = get()
val b : UByteArray = get()

if (a == b) println("The same stuff")

Is the equality operator sufficient, or do I have to compare the two byte for byte?


Solution

  • UByteArray and other arrays of unsigned types have their equality operation defined so that it is consistent with the equality of signed type arrays, hence two UByteArrays are equal only when they refer to the same instance.

    The structural equality of two UByteArrays can be found with the extension function contentEquals, same as for the signed arrays:

    val ubyteArray1 = ubyteArrayOf(1u, 2u, 3u)
    val ubyteArray2 = ubyteArrayOf(1u, 2u, 3u)
    println(ubyteArray1 contentEquals ubyteArray2)