3

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

case object Foo

or

object Foo extends Serializable

?

Jim Ferrans
  • 30,582
  • 12
  • 56
  • 83
soc
  • 27,983
  • 20
  • 111
  • 215

1 Answers1

2

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.

Dan Simon
  • 12,891
  • 3
  • 49
  • 55