I thought only data classes have `equals/hashcode`...
# getting-started
n
I thought only data classes have 
equals/hashcode
 method implemented by default. But it turns out,
Copy code
class SomeClass(val a: String)

fun main(){
    val someClass1 = SomeClass("abcd")
    val someClass2 = SomeClass("abcd")

    println(someClass1 == someClass2) // this code is also valid
}
==
is also supported in regular classes. How does it behave? Is
==
is same as
===
in case of non-data classes?
p
all objects in Kotlin implement
equals()
and
hashcode()
, they're just almost always useless (because they're referential equality, rather than structural equality). Your example probably only appears to work because your JVM is using the same interned string instance for "abcd", but there's no guarantee it will do that
==
vs
===
always means 'structural equality operator' vs 'referential equality operator', it's just that without manually defined
equals
there's nothing to use on a given object besides the referential equality
n
I see. But in the snippet,
println(someClass1 == someClass2)
this code prints
false
, as expected. Because
someClass1
and
someClass2
don't reference the same object. So, effectively
==
would be same as
===
in normal classes unless
equals
is overridden with some custom logic.
c
@nilTheDev Exactly:
==
(or
equals
) let's you define a custom way to represent equality. It is defined in
Any
, so you can use it for whatever class. The default implementation is to use
===
.
data class
have a better default implementation, which uses properties; but it is defined for any Kotlin objects.
1
💙 1