Let’s see how we can apply Joshua Bloch’s Effective Java in the Kotlin world. Today’s topic is Methods Common to All Objects.
Item 10: Obey the general contract when overriding equals
In Kotlin, we should use data classes for classes that represent values. The compiler will automatically generate hashCode(), equals() and other methods.
data class MyDataClass(val someValue: Int, var anotherValue: String)Item 11: Always override hashCode when you override equals
See Item 10 for using data classes.
Item 12: Always override toString
Again, See Item 10 for using data classes.
Item 13: Override clone judiciously
As expected, when using data classes, the compiler will generate the copy() function. With the example in Item 10, it looks like something below:
fun copy(
someValue: Int = this.someValue,
anotherValue: String = this.anotherValue
) = MyDataClass(someValue, anotherValue)Item 14: Consider implementing Comparable
We should use the Comparable from Kotlin’s standard library instead of the Java one, which also provides lots of extension functions.