Sealed Class with Extra Data: IsExpected
sealed class IsExpected(val isExpected: Boolean) {
data class NonExpected(val message: String) : IsExpected(isExpected = false)
object Expected : IsExpected(isExpected = true)
}
Note: Explanation of IsExpected
Design
The IsExpected
sealed class is designed to represent whether something is expected or not, with two distinct cases:
-
NonExpected
:- A data class representing the case where something is not expected.
- It includes a
message
property to provide additional context or explanation for why it is not expected. - The
isExpected
property is alwaysfalse
.
-
Expected
:- An
object
representing the case where something is expected. - The
isExpected
property is alwaystrue
.
- An
Why Use object
for Expected
?
An object
is used for Expected
instead of a class
or data class
because:
-
Singleton Representation:
- The
Expected
case does not require any additional state beyond theisExpected
boolean (which is alwaystrue
). - Using an
object
ensures that only a single instance ofExpected
exists, as opposed to creating a new instance every time it is referenced.
- The
-
Memory Efficiency:
- As
Expected
has no properties other than the inheritedisExpected
, using anobject
avoids the overhead of creating multiple instances. It’s more efficient to use a single shared instance.
- As
-
Semantic Clarity:
- An
object
clearly communicates that theExpected
case is a fixed, immutable concept with no variability. It doesn’t require construction or additional parameters. - This makes the design more intuitive and aligns with the idea that the
Expected
case is inherently simple and unchanging.
- An
-
Simpler Equality:
- For an
object
, equality checks are always by reference since there’s only one instance. This simplifies comparisons likeif (value is Expected)
.
- For an
Why Not Use object
for NonExpected
?
NonExpected
uses a data class
because it contains additional information (message
) that varies between instances. Each NonExpected
instance can have different data, which is why it requires the ability to hold state and support value-based equality.
Summary
The use of an object
for Expected
is an intentional design choice that reflects its simplicity, immutability, and singleton nature. In contrast, NonExpected
uses a data class
because it needs to store varying information for different instances. This distinction ensures clarity, efficiency, and correctness in the design of the IsExpected
sealed class.