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:

  1. 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 always false.
  2. Expected:

    • An object representing the case where something is expected.
    • The isExpected property is always true.

Why Use object for Expected?

An object is used for Expected instead of a class or data class because:

  1. Singleton Representation:

    • The Expected case does not require any additional state beyond the isExpected boolean (which is always true).
    • Using an object ensures that only a single instance of Expected exists, as opposed to creating a new instance every time it is referenced.
  2. Memory Efficiency:

    • As Expected has no properties other than the inherited isExpected, using an object avoids the overhead of creating multiple instances. It’s more efficient to use a single shared instance.
  3. Semantic Clarity:

    • An object clearly communicates that the Expected 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.
  4. Simpler Equality:

    • For an object, equality checks are always by reference since there’s only one instance. This simplifies comparisons like if (value is Expected).

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.