nilTheDev
09/06/2021, 2:02 PMequals/hashcode
method implemented by default.
But it turns out,
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?Paul Griffith
09/06/2021, 2:50 PMequals()
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 equalitynilTheDev
09/06/2021, 2:55 PMprintln(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.CLOVIS
09/06/2021, 3:10 PM==
(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.