Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of a Object Declaration inside a Sealed Class in Kotlin?

Tags:

kotlin

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()?

like image 270
jmrah Avatar asked Mar 12 '17 19:03

jmrah


1 Answers

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.

like image 141
zsmb13 Avatar answered Oct 16 '22 04:10

zsmb13