JP
05/28/2020, 6:50 AMhashCode()
and toString()
implementation for the cases where I don’t define a class as data class?
For example when I examined with a class like this:
class ListNode(var elem: Int) {
var next: ListNode? = null
}
fun main() {
val node = ListNode(123)
println(node.hashCode()) // 895328852
println(node.toString()) // ListNode@355da254
node.elem = 456
println(node.hashCode()) // 895328852
println(node.toString()) // ListNode@355da254
}
whereas when I examined when changing to data class:
data class ListNode(var elem: Int) {
var next: ListNode? = null
}
fun main() {
val node = ListNode(123)
println(node.hashCode()) // 123
println(node.toString()) // ListNode(elem=123)
node.elem = 456
println(node.hashCode()) // 456
println(node.toString()) // ListNode(elem=456)
}
From this my assumption is that the hashCode()
and toString()
depends on the memory address when the class is not a data class, whereas in case of data class, it will not depend on the memory address but the properties which are defined in the primary constructor (which makes sense, since that would be what data classes are for and how they should behave).
Is my assumption correct?
And where can I see these default implementations for hashCode()
, both for class and data class? I wasn’t able to find them.araqnid
05/28/2020, 8:33 AMMatteo Mirk
05/28/2020, 8:40 AMdata
classes, rather with a class overriding or not such methods. The default implementations are defined in Any
which is the topmost class in the type hierarchy (similar to Java’s Object
), but you can’t see them in the source code as they are synthesized by the compiler I guess. As you noted the default hashCode is computed in some way and toString depends on the memory address. When you override those method you can make them return anything you like, although you should respect their contract. For data classes the compiler generates those implementation (along with other methods) which depend on all and only fields declared in the constructor.JP
05/28/2020, 12:08 PMMatteo Mirk
05/29/2020, 8:43 AMAny
implementation as many standard lib classes implement their own, and in your classes you’re encouraged to implement toString() if you need a readable or meaningful string representation, and equals/hashcode contract (always together) if your class needs to be used inside collections.JP
05/29/2020, 11:09 AMhashCode()
function.Matteo Mirk
05/29/2020, 12:52 PM