Equals method for data class in Kotlin

后端 未结 3 698
半阙折子戏
半阙折子戏 2020-12-24 10:21

I have the following data class

data class PuzzleBoard(val board: IntArray) {
    val dimension by lazy { Math.sqrt(board.size.toDouble()).toInt() }
}
         


        
3条回答
  •  半阙折子戏
    2020-12-24 11:10

    In Kotlin, equals() behaves differently between List and Array, as you can see from code below:

    val list1 = listOf(1, 2, 3)
    val list2 = listOf(1, 2, 3)
    
    val array1 = arrayOf(1, 2, 3)
    val array2 = arrayOf(1, 2, 3)
    
    //Side note: using a==b is the same as a.equals(b)
    
    val areListsEqual = list1 == list2// true
    val areArraysEqual = array1 == array2// false
    

    List.equals() checks whether the two lists have the same size and contain the same elements in the same order.

    Array.equals() simply does an instance reference check. Since we created two arrays, they point to different objects in memory, thus not considered equal.

    Since Kotlin 1.1, to achieve the same behavior as with List, you can use Array.contentEquals().

    Source: Array.contentEquals() docs ; List.equals() docs

提交回复
热议问题