Reputation: 8126
I want to create on-the-fly objects using object expressions but I would like to compare them by their contents. Is there an easy way to write it without implementing equals
and hashCode
?
To make it more concrete, what would be the smallest change to make the assertion of this test pass?
@Test
fun `an object comparison test`() {
val obj1 = object {
val x = 1
}
val obj2 = object {
val x = 1
}
assertEquals<Any>(obj1, obj2)
}
Upvotes: 0
Views: 35
Reputation: 23252
Without implementing a corresponding equals
(at least) they will never be equal. That's the nature of every object
or instance
you create. Exceptions to that are data class
instances which actually already supply an appropriate equals()
/hashCode()
for you.
So
data class Some(val value : String)
println(Some("one") == Some("one"))
will actually print true
even though these are two distinct instances.
The easiest is probably to supply your own assertion function (may it be via reflection or not) or use a reflective assertion equals-method if your test framework supplies it. In the latter case maybe the following is interesting for you: How do I assert equality on two classes without an equals method?
Upvotes: 2