Compare two objects for equality in Kotlin
This article explores different ways to compare two objects for equality in Kotlin.
The recommended option to compare two objects in Kotlin is using the == operator, which gets compiled to the equals() function. However, simply calling the == operator might not work as expected, as shown below:
|
1 2 3 4 5 6 7 |
class TV(var company: String, var model: String, var warranty: Int) fun main() { val tv1 = TV("Vu", "Premium 4K", 2) val tv2 = TV("Vu", "Premium 4K", 2) println(tv1 == tv2) // false } |
This post provides an overview of some of the available alternatives to compare two objects for equality using the == operator.
1. Overriding equals() and hashCode() function
Every class should override the equals and hashCode function to specify the equivalence relation between objects. A typical implementation of this approach would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class TV(private var company: String, private var model: String, private var warranty: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TV if (company != other.company) return false if (model != other.model) return false if (warranty != other.warranty) return false return true } override fun hashCode(): Int { var result = company.hashCode() result = 31 * result + model.hashCode() result = 31 * result + warranty return result } } fun main() { val tv1 = TV("Vu", "Premium 4K", 2) val tv2 = TV("Vu", "Premium 4K", 2) println(tv1 == tv2) // true } |
2. Using Data class
Instead of overriding the equals() and hashCode() functions, you can use a data class that automatically derives the equals() and hashCode().
|
1 2 3 4 5 6 7 |
data class TV(private var company: String, private var model: String, private var warranty: Int) fun main() { val tv1 = TV("Vu", "Premium 4K", 2) val tv2 = TV("Vu", "Premium 4K", 2) println(tv1 == tv2) // true } |
3. Using custom routine
If you prefer not to use data class or override the equals() and hashCode() function, create a custom routine to check for equality. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class TV(var company: String, var model: String, var warranty: Int) fun isEqual(tv1: TV, tv2: TV?): Boolean { return if (tv1 === tv2) { true } else if (tv2 == null || tv1.javaClass != tv2.javaClass) { false } else { tv1.warranty == tv2.warranty && tv1.company == tv2.company && tv1.model == tv2.model } } fun main() { val tv1 = TV("Vu", "Premium 4K", 2) val tv2 = TV("Vu", "Premium 4K", 2) println(isEqual(tv1, tv2)) // true } |
That’s all about comparing two objects for equality in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)