TL ; DR:
For objects, == calls equals. By default, it asks if two variables hold the very same object. Override equals to compare the values instead. Override hashCode too, so a HashSet or a HashMap can find equal objects.
override fun equals(other: Any?): Boolean {
return other is Time && hour == other.hour && minute == other.minute
}
override fun hashCode(): Int {
return 31 * hour + minute
}
Full lesson:
Two objects can hold the same values and still be two objects.
val a = Time(9, 30)
val b = Time(9, 30)
println(a == b) // false
a == b calls a.equals(b). Every class inherits equals from Any. By default it checks identity. It is true only when both variables hold one and the same object.
Equal by value
Override equals(other: Any?) to compare the fields.
other is Time checks that other is a Time. After that check, Kotlin lets you read other.hour directly.
Sets need a hash code
A HashSet doesn't compare a new item with every item it holds. That would be slow. It files each object under a number, its hash code. Then it calls equals only on objects with the same hash code.
So equal objects must have equal hash codes. hashCode() returns that number. 31 * hour + minute mixes both fields into one number. Equal times give equal numbers.
A shortcut
A data class writes equals and hashCode for you. A later lesson shows it. Here you write them yourself, to see how they work.
Your task
The Time class keeps an hour and a minute. Override equals and hashCode. Two times are equal when the hour and the minute both match.
mainFunction compares three times. Then it puts them in a HashSet of alarms.
Expected output:
a and b are the same time
a and c are different times
alarms: 2Free plan: 30 tutor messages. Premium is unlimited.
