In the Kotiln documentation, they give the following example for sealed classes:
sealed class Expr {
class Const(val number: Double) : Expr()
class Sum(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()
}
What would be the use of delcaring NotANumber
as a object declaration (singleton?) here? Why not just write class NotANumber : Expr()
?
Since it doesn't contain a significant value, the single instance of it can be reused everywhere. This saves you the creation cost of this object where you need it.
Another example of this would be Kotlin's Unit
, which is also just an object
.
This is just one of the examples of how you can avoid creating unnecessary instances that the garbage collector then has to clean up. Another example would be how the Java BigInteger
class has final static fields for constants like ZERO
and ONE
. Although these do contain state, they are immutable, so they can be just one instance each that's reused and don't have to be re-created all the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With