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:
otheris of typeAny?, the check forother is Personsmartcasts it toPerson, which makes thefirstNameproperty available.Long Answer: A few things to note about this question and the code:
data class,equalsandhashCodeare 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 likeHashMaporHashSet. Again, if you're usingdata class, no need to worry about this.valinstead ofvarup to the point where it doesn't work anymore (because you have to reassign it). Usingvarcan disable smart casts in a lot of situations and therefore make your code less elegant. In your example, all occurrences ofvarcan most likely be swapped out forval.==operator to check whetherthis.firstNameis equal toother.firstName, you can (and should) use==to comparepersonObj1andpersonObj2in yourmainfunction. See operator overloading.to just
In your snippet, there's no
elsebranch, but still the implementation could be simplified to(see also: expression functions)