Search code examples
scalaserializationobjectsingletonlanguage-design

Recommended code style: case object Foo or object Foo extends Serializable?


If I want a serialization-safe singleton, should I prefer

case object Foo

or

object Foo extends Serializable

?


Solution

  • I think this depends on how you plan to use this object. Case objects are generally used with case classes to represent some kind of initial or terminal object in an algebraic data type, eg Nil or None. Regular objects usually are companions for classes to hold static methods like singleton and factory methods.

    If you're planning using this object with other classes, serializing it, and maybe using it in pattern matching, defining it as a case object seems more natural to me.