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 Set or a Map can find equal objects.
override def equals(other: Any): Boolean = other match {
case t: Time => hour == t.hour && minute == t.minute
case _ => false
}
override def hashCode(): Int = (hour, minute).hashCode()
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.
A match checks what other is. The case t: Time runs when it is a Time, and names it t. Anything else falls to case _, which gives false.
Sets need a hash code
A Set 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. (hour, minute).hashCode() builds it from a tuple of the same fields as equals.
A shortcut
A case 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 Set 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.
