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
messageproperty to provide additional context or explanation for why it is not expected. - The
isExpectedproperty is alwaysfalse.
-
Expected:- An
objectrepresenting the case where something is expected. - The
isExpectedproperty 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
Expectedcase does not require any additional state beyond theisExpectedboolean (which is alwaystrue). - Using an
objectensures that only a single instance ofExpectedexists, as opposed to creating a new instance every time it is referenced.
- The
-
Memory Efficiency:
- As
Expectedhas no properties other than the inheritedisExpected, using anobjectavoids the overhead of creating multiple instances. It’s more efficient to use a single shared instance.
- As
-
Semantic Clarity:
- An
objectclearly communicates that theExpectedcase 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
Expectedcase 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.