Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 134 ยท Classes and Objects

Object Basics: toString, equals, hashCode

Learn the three functions every Kotlin object inherits from Any: write readable toString output, implement hashCode correctly, and avoid mutable-key and cyclic-reference traps.

Every Kotlin class, whether you write class Plain or data class User(...), quietly inherits from Any. And Any provides exactly three functions: toString(), equals(other) and hashCode(). They are the common language that printing, collections, debuggers and test frameworks use to talk to your objects. If you get them right, a println(user) is readable, a HashSet<User> behaves, and failing tests tell you what went wrong. If you get them wrong, you see User@1b6d3586 in your logs and a map that mysteriously "loses" entries.

Equality and Identity explained ==, === and the equals contract. This lesson focuses on the practical side: writing a helpful toString, a correct and well-distributed hashCode, how data classes do all this for you, and the traps that remain (mutable keys, cyclic references and secrets in output).

The default toString is useless

If you do not override toString, the inherited version returns the class name, an @ sign and the object's identity hash code in hexadecimal. The part after @ changes from run to run, so never depend on it, and never show it to users:

Kotlin The inherited toString

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A string template like "user: $user" and println(user) both call toString() behind the scenes, and so does a collection when it prints its elements. That is why one small override improves every log line.

Writing a helpful toString

A good toString is for humans (developers reading logs, tests, debuggers). It should show the class name and the values that identify the object, in a stable format. It should be cheap, side-effect free, and never throw.

Kotlin Overriding toString

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Note that listOf(...) printing uses each element's own toString. Two guidelines: do not use toString() as a data format (parsing it later is fragile; write an explicit toJson() or serialize() instead), and keep it free of user-facing text that should be translated.

Data classes generate it

A data class generates toString from its primary constructor properties in the form Name(prop=value, ...), and also generates equals and hashCode from the same properties. You can still override any of them:

Kotlin Generated and customized toString

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The second class shows a security rule: never print secrets. A generated toString prints every constructor property, which means a password, token or card number lands in your logs, exception messages and crash reports. Override toString to mask such fields (or keep them out of the primary constructor).

hashCode: the number behind hash collections

hashCode() returns an Int summary of an object. HashMap, HashSet, LinkedHashMap (and the default mapOf, setOf, mutableMapOf) use it to find the right "bucket" in constant time, and then use equals to check the candidates inside it. The rules are:

  1. Consistency with equals: if a == b, then a.hashCode() == b.hashCode().
  2. Stability: the result must not change while the object is in a hash collection.
  3. Good spread (not required but important): different objects should usually give different numbers. If everything returns 42, a hash map degrades into a slow linked list.

The standard recipe multiplies and adds: start with the hash of the first field, then for every other field compute 31 * result + field.hashCode(). The multiplier 31 is an odd prime, which spreads values well and is cheap for the JVM to compute. java.util.Objects.hash(...) does exactly that for you:

Kotlin Writing hashCode by hand and with Objects.hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The last two lines show that standard classes follow the same recipe, and, importantly, that their results are specified: a String always hashes the same way, even across runs. That is not true for plain objects that use the identity hash. For a data class you never write this by hand; the compiler generates it from all constructor properties, in the same spirit.

Do not use hashCode() for anything else: it is not unique, not a checksum, not a stable identifier you can store in a database, and its algorithm may change in a future version. For a real identifier use an explicit id.

The mutable key trap

A hash collection files an object into a bucket when you add it, using the hash at that moment. If you later change a field that takes part in hashCode, the object is still in the old bucket, but lookups now search a different one. The element becomes a ghost: it is counted by size, found by iteration, but not found by contains, and impossible to remove:

Kotlin Mutating a key after insertion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The set is corrupt, and no exception tells you so. The remedy is simple: use immutable (val) properties for anything that takes part in equals/hashCode, and never mutate objects used as map keys or set elements. This is the biggest reason data classes should have val properties.

The cycle trap

If two objects reference each other, a generated or hand-written toString (or hashCode, or equals) that visits every property will follow the arrow forever:

Kotlin A cyclic toString (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program ends with Exception in thread "main" java.lang.StackOverflowError, because toString of ana calls toString of boss, which calls toString of ana, and so on. (A property declared in the body, like other in Node, is ignored by the generated functions, which is why it is safe.) Fixes: keep the back-reference out of the primary constructor, or override toString to print only the other object's name:

Kotlin Breaking the cycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A checklist for your own classes

  • Do you need equals? If instances are just data, use a data class and stop here.
  • If you write equals, write hashCode from the same fields.
  • Use only val fields in equals/hashCode when the object may go into a hash collection.
  • Override toString for everything you will ever log; mask secrets.
  • Keep all three cheap and free of side effects. Never do I/O or lazy loading inside them.
  • Watch cycles and very large nested structures (a toString of a million-element list is a performance bug in a log line).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the inherited Any.toString() return for class Plain?

    The default is ClassName@hexHash. It is not meant for humans and changes between runs.
  2. 2. Which rule must hashCode obey with respect to equals?

    Equal objects must produce equal hash codes. Unequal objects may share a hash code (a collision), only less efficiently.
  3. 3. What happens when you change a var property used in hashCode after adding the object to a HashSet?

    The object stays in the old bucket while lookups use the new hash, so it becomes unreachable by key, but still present in size and iteration.
  4. 4. Why should you override toString in data class Login(val user: String, val password: String)?

    The generated function prints every primary-constructor property. Override it to mask sensitive values.
  5. 5. A generated data class toString ends with StackOverflowError. What is the most likely cause?

    toString recursively prints referenced objects; a reference cycle never ends. Break the cycle or override toString.

Summary

  • Every object inherits toString, equals and hashCode from Any; collections, printing and test tools depend on them.
  • The default toString prints ClassName@hash; override it with a readable, cheap, safe representation, and mask secrets.
  • hashCode must agree with equals; the usual recipe is 31 * result + field.hashCode(), or Objects.hash(...).
  • Do not mutate fields used in hashCode while the object is a map key or set element.
  • Reference cycles break generated toString, equals and hashCode with StackOverflowError.
  • For plain data holders, a data class generates all three correctly.

Next: Encapsulation and Design