Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the compiler suggest convert sealed sub-class to object?

I don't understand why the compiler suggests me to convert a sealed class with the subclasses, to objects, let see an example:

sealed class CallState
class SendReceive : CallState()
class SendOnly:CallState()

to this

sealed class CallState
object SendReceive : CallState()
object SendOnly:CallState()

Seems like it is preventing me from creating a not state object, but I don't know what the compiler means.

Thanks for your help.

like image 548
dicarlomagnus Avatar asked Mar 26 '20 17:03

dicarlomagnus


2 Answers

The compiler says

Sealed sub-class has no state and no overridden equals, convert sealed sub-class to object

From this you can deduce that if e.g. SendReceive had state, the warning would go away. And indeed, if you change the declaration to

class SendReceive(val i: Int) : CallState()

and thus add an Int state to the class, then the warning goes away.

The explanation is simple. If there is no difference between different instances of SendReceive, why allow different instances? Making it an object makes it single-instance, which makes perfect sense to do when different instances are not different in any way.

like image 72
Enselic Avatar answered Oct 14 '22 15:10

Enselic


sealed classes are similar to enum in java but it allows to keep state. if a subclass doesn’t keep state, it can just be an object.

SendReceive is object but SenOnly will be class.

sealed class CallState {
    object SendReceive : CallState()
    class SendOnly(var totalReceiver:Int) : CallState()
}
like image 22
Junaid Avatar answered Oct 14 '22 13:10

Junaid