11

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.

dicarlomagnus
  • 576
  • 4
  • 17
  • 2
    I think I'm missing something but... If your class does not contain any state, why not use an enum instead ? In fact, the big sealed class advantage is that two instances of the same class can contain different values. However, without state, the only benefit is finite hierarchy, and that can be tested with static objects, no need of multiple instances. That would surely save memory at runtime (but in that case, enums are surely even more optimized). – amanin Mar 26 '20 at 18:38
  • Making them classes can be useful with some reflection-based libraries which don't understand Scala objects (e.g. for de/serialization), but then consider using a library which does understand them instead. – Alexey Romanov Mar 27 '20 at 08:10

2 Answers2

15

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.

Enselic
  • 4,434
  • 2
  • 30
  • 42
  • Some more details on why `object` means single instance: https://medium.com/androiddevelopers/the-one-and-only-object-5dfd2cf7ab9b – dshepherd Oct 31 '22 at 07:25
3

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()
}
Junaid
  • 1,301
  • 1
  • 15
  • 21