I've been working on overriding the equals() from Any class. But in the below code. I'm confused why "if (other is Person)" is necessary to get the "if(this.firstName == other.firstName)" statement to work.
fun main()
{
var personObj1 = Person("Adam","S")
var personObj2 = Person("Adam","S")
println(personObj1.equals(personObj2))
}
class Person(var firstName:String, var lastName:String)
{
override fun equals(other: Any?): Boolean {
if (other is Person) {
if (this.firstName == other.firstName) {
return true
}
}
return false
}
}
Without the if(other is Person) statement, code gives the below error
Short Answer:
other
is of typeAny?
, the check forother is Person
smartcasts it toPerson
, which makes thefirstName
property available.Long Answer: A few things to note about this question and the code:
data class
,equals
andhashCode
are generated automatically and you don't have to implement them. Check the documentation about data classes to find out whether they are applicable in your situation (they probably are).hashCode()
IF you manually overrideequals()
and vice versa. Not doing so can lead to serious performance problems or even bugs when using hash-based data structures likeHashMap
orHashSet
. Again, if you're usingdata class
, no need to worry about this.val
instead ofvar
up to the point where it doesn't work anymore (because you have to reassign it). Usingvar
can disable smart casts in a lot of situations and therefore make your code less elegant. In your example, all occurrences ofvar
can most likely be swapped out forval
.==
operator to check whetherthis.firstName
is equal toother.firstName
, you can (and should) use==
to comparepersonObj1
andpersonObj2
in yourmain
function. See operator overloading.to just
In your snippet, there's no
else
branch, but still the implementation could be simplified to(see also: expression functions)