https://kotlinlang.org logo
#getting-started
Title
# getting-started
n

nilTheDev

09/06/2021, 2:02 PM
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

Paul Griffith

09/06/2021, 2:50 PM
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

nilTheDev

09/06/2021, 2:55 PM
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

CLOVIS

09/06/2021, 3:10 PM
@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