https://kotlinlang.org logo
Title
b

bod

11/29/2018, 12:44 PM
Hello, World! Is there any documentation somewhere about how
equals
work for sealed classes?
d

diesieben07

11/29/2018, 12:47 PM
It works exactly the same as everywhere else.
b

bod

11/29/2018, 12:54 PM
it’s not completely obvious for me 🙂 In my case I have a sealed class with 2 possible values: one object, and one data class. In case I compare 2 instances of the data class, will the equals of the data class be called?
d

diesieben07

11/29/2018, 12:56 PM
Yes, the call
equals
is a call to a polymorphic function. The exact function to call (
equals
in
Any
or
equals
in your data class, etc.) is determined at runtime based on the actual type of the object.
b

bod

11/29/2018, 12:59 PM
oh so by default the
equals
of the “sub type” is used. Makes sense. What if I override the
equals
of the sealed class however?
is it even used? 🙂
d

diesieben07

11/29/2018, 1:00 PM
It's a normal polymorphic method call. The method "furthest down" in the inheritance chain will be called. If you have:
A extends B extends C
and only
B
has
equals
then objects of type
C
will use that equals.
b

bod

11/29/2018, 1:02 PM
all right it makes sense 🙂 Thanks a lot!