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) } 
2
  • 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. Commented Jul 26, 2018 at 11:24
  • Thanks @yole. That makes sense. Commented Jul 26, 2018 at 12:01

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.