A non-var on a case class


I have a class with no arguments in its constructor.
I always construct it using new and use its methods to populate it with the appropriate data.
But as my program is advancing, I’d like to have some smarter factory functions.

Is the correct way to create factory functions to create an object with the same name as the class,
and give that object several apply methods of different arity?

Or should I create several this methods inside the class definition?

I’m hesitant of creating a case class because I don’t really need the initialization value to hang around. In some cases this value will be huge in terms of memory requirement, and what I need is a massaged form of this to be kept around. If I define the class as case class Foo(x) that means that when I call f = Foo(data), then data won’t be GC’able until the f is GC’able. Right?


Both are legit, but I’ve seen a lot more of the object-based factory functions in recent years, and I generally find that approach more flexible and a bit easier to use in practice.

Yes, I believe that’s always true.


You can always use a var in the constructor and set it to null after using it to populate the class?


Yeah, but I would say that’s an anti-pattern for a case class. The other choices are cleaner.