How to compare two arrays in Kotlin?

前端 未结 5 1318
生来不讨喜
生来不讨喜 2020-12-08 18:59

Given some arrays in Kotlin

let a = arrayOf(\"first\", \"second\")
val b = arrayOf(\"first\", \"second\")
val c =          


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 19:12

    In Kotlin 1.1 you can use contentEquals and contentDeepEquals to compare two arrays for structural equality. e.g.:

    a contentEquals b // true
    b contentEquals c // false
    

    In Kotlin 1.0 there are no "built-in functions to the Kotlin std-lib that tests two arrays for (value) equality for each element."

    "Arrays are always compared using equals(), as all other objects" (Feedback Request: Limitations on Data Classes | Kotlin Blog).

    So a.equals(b) will only return true if a and b reference the same array.

    You can, however, create your own "optionals"-friendly methods using extension functions. e.g.:

    fun Array<*>.equalsArray(other: Array<*>) = Arrays.equals(this, other)
    fun Array<*>.deepEqualsArray(other: Array<*>) = Arrays.deepEquals(this, other)
    

    P.S. The comments on Feedback Request: Limitations on Data Classes | Kotlin Blog are worth a read as well, specifically comment 39364.

提交回复
热议问题