https://kotlinlang.org logo
#announcements
Title
# announcements
c

cedric

04/16/2017, 2:40 PM
@Paul Woitaschek Helper methods to generate these for you would require reflection, and
equals()
and
hashCode()
are not methods where you want to do that. Guava has some helper methods, though: https://gist.github.com/rocketraman/1399080/a50ea2206f6ea4bda65ef00d1f54aab6d654d3bd
👍 2
p

Paul Woitaschek

04/17/2017, 7:31 AM
Why does it need reflection? That compareTo has helpers too where you can specify a comparision chain
I was thinking about sth like
Copy code
fun hashCodeOf(vararg elements: Any?): Int {
    var hash = 17
    elements.forEach {
      hash = hash * 31 + (it?.hashCode() ?: 0)
    }
    return hash
  }
c

cedric

04/17/2017, 2:16 PM
@Paul Woitaschek A method that would be able to generically compute hashcode/equals would need to reflect on your class. Guava picked the better approach of offering helper methods you’d use inside your own implementation of equals/hashCode
p

Paul Woitaschek

04/17/2017, 4:18 PM
My function is made to be used inside my own implementation of hashcode.