Equality Workbook
Practice problems for In Kotlin, == Is the One You Actually Want. Each takes a minute or two. Write your own answer first, then click Show answer — nothing here is a trick question, just direct practice of the syntax from the lesson.
== versus ===
1. Value or identity
Write code that builds two Strings with equal contents but as different objects, then both comparisons — annotate what each returns.
Show answer Hide answer
val a = "hello"
val b = StringBuilder("hel").append("lo").toString()
a == b // true — equal contents (calls .equals())
a === b // false — different objects 2. Null-safe comparison
Given a: String? and b: String?, write the comparison that’s true when they hold equal text or are both null — with no explicit null check.
Show answer Hide answer
a == b== calls .equals() and handles null on both sides, so null == null is true and neither side throws.
3. Null-safe by default
Given a: String? and b: String?, compare them for value equality. What happens if both are null?
Show answer Hide answer
a == b== handles null on both sides without throwing — null == null is true. No Objects.equals wrapper needed.
4. Detect a fresh copy
Write code that confirms toList() produced a new object whose contents still equal the original.
Show answer Hide answer
val a = listOf(1, 2, 3)
val b = a.toList()
a == b // true — same contents
a === b // false — toList() allocated a new list defining equality
5. Free value equality
Declare a type Point so that Point(1, 2) == Point(1, 2) is true without writing equals yourself.
Show answer Hide answer
data class Point(val x: Int, val y: Int) 6. Works correctly in a HashSet
Declare a Point type so two equal points are deduplicated by a HashSet (its equals and hashCode must agree). Show the resulting size.
Show answer Hide answer
data class Point(val x: Int, val y: Int)
hashSetOf(Point(1, 1), Point(1, 1)).size // 1data class generates equals and a matching hashCode — the contract hash-based collections rely on.
ordering
7. Make a type comparable
Make Version(val major: Int, val minor: Int) implement Comparable so < and > work, comparing major first then minor.
Show answer Hide answer
class Version(val major: Int, val minor: Int) : Comparable<Version> {
override fun compareTo(other: Version) =
compareValuesBy(this, other, { it.major }, { it.minor })
} 8. Use the operator
Given the Version above, write the expression comparing whether Version(2, 1) is greater than Version(2, 0).
Show answer Hide answer
Version(2, 1) > Version(2, 0) // true> delegates to compareTo.
9. Sort by a key
Given a list people of objects with an age, return them sorted youngest first.
Show answer Hide answer
people.sortedBy { it.age } 10. Sort by two keys
Sort people by lastName, then firstName as a tiebreaker.
Show answer Hide answer
people.sortedWith(compareBy({ it.lastName }, { it.firstName })) Back to the lesson, In Kotlin, == Is the One You Actually Want, or on to the next one: destructuring.