0

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)
}
alisabzevari
  • 8,008
  • 6
  • 43
  • 67
  • 1
    No, there is no way. These two objects are instances of two different classes with no relationship between each other. Whenever the compiler or IDE generates `equals()` for you, it requires that the objects have the same class. – yole Jul 26 '18 at 11:24
  • Thanks @yole. That makes sense. – alisabzevari Jul 26 '18 at 12:01

1 Answers1

2

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?

Roland
  • 22,259
  • 4
  • 57
  • 84