I have the following data class
data class PuzzleBoard(val board: IntArray) {
val dimension by lazy { Math.sqrt(board.size.toDouble()).toInt() }
}
I read that data classes in Kotlin get equals()/hashcode() method for free.
I instantiated two objects.
val board1 = PuzzleBoard(intArrayOf(1,2,3,4,5,6,7,8,0))
val board2 = PuzzleBoard(intArrayOf(1,2,3,4,5,6,7,8,0))
But still the following statements return false.
board1 == board2
board1.equals(board2)
In Kotlin,
equals()
behaves differently betweenList
andArray
, as you can see from code below: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 useArray.contentEquals()
.Source: Array.contentEquals() docs ; List.equals() docs
For Data classes in Kotlin, hashcode() method will generate and return the same integer if parameters values are same for both objects.
Running this code will return True and False as when we created secondUser object we have passed same argument as object user, so hashCode() integer generated for both of them will be same.
also if you will check this:
It will return false.
As per hashCode() method docs
For more details see this discussion here
In Kotlin
data
classes equality check, arrays, just like other classes, are compared usingequals(...)
, which compares the arrays references, not the content. This behavior is described here:Given that,
To override this and have the arrays compared structurally, you can implement
equals(...)
+hashCode()
in your data class usingArrays.equals(...)
andArrays.hashCode(...)
:This code is what IntelliJ IDEA can automatically generate for non-data classes.
Another solution is to use
List<Int>
instead ofIntArray
. Lists are compared structurally, so that you won't need to override anything.