I am trying to write an assertion by comparing two Kotlin data classes.I am just simplifying the question by using a minimal class.
data class X(val isThatSo: Boolean) {
val name:String = "xyz"
}
In my test
val s = """
{
"isThatSo": "true",
"name": "Ankit"
}
"""
assert(Gson().fromJson(s, X::class.java) == X(true))
Looks to me that the name field is not compared at all because the value in both the objects is different. Is my understanding correct?
CodePudding user response:
From the documentation:
data class User(val name: String, val age: Int)
The compiler automatically derives the following members from all properties declared in the primary constructor:
equals()/hashCode()
pair
toString()
of the form "User(name=John, age=42)"
componentN()
functions corresponding to the properties in their order of declaration.
copy()
function.To exclude a property from the generated implementations, declare it inside the class body:
data class Person(val name: String) { var age: Int = 0 }
CodePudding user response:
You're comparing two instances of a class, which are not identical. You can compare the name
variable within X
for equality.