Globally accessible immutable instance of case class

#1

What is the correct way to great a default instances of a case class?
If it is not a case class, but rather a normal class, then I can create singleton instances like this:

sealed abstract class BddTerm extends Bdd {}

object BddTrue extends BddTerm {}

object BddFalse extends BddTerm {}

In my application I have several classes such as the following:

case class RemoveAdd(removes:List[ClauseDesignator], adds:List[ClauseDesignator])

It it seems like certain fold expressions get called millions of times in the core loop of the program which uses what I call a default object creating by calling RemoveAdd(Nil,Nil).

I tried to define an instance at the top level, but it seems to be impossible.

case class RemoveAdd(removes:List[ClauseDesignator], adds:List[ClauseDesignator])
val RemoveAddNil = RemoveAdd(Nil,Nil)

But I get an error, Wrong top level statement

If I try to create a top level object, it fails at the call site

case class RemoveAdd(removes:List[ClauseDesignator], adds:List[ClauseDesignator])
object RemoveAddNil extends RemoveAdd(Nil,Nil)
Error:(122, 52) constructor cannot be instantiated to expected type;
 found   : dimacs.RemoveAdd
 required: dimacs.RemoveAddNil.type
    compatiblePairs.foldLeft(RemoveAddNil) { case (RemoveAdd(removes, adds), (aa, bb)) =>
Error:(124, 16) type mismatch;
 found   : dimacs.RemoveAdd
 required: dimacs.RemoveAddNil.type
      RemoveAdd(ClauseDesignator(aa, posCount, length, rectified) :: ClauseDesignator(bb, posCount - 1, length, rectified) :: removes,

QUESTION: What is the correct and idiomatic way of doing this?

#2

I would put those fixed instances in the companion object.

case class RemoveAdd(removes: List[ClauseDesignator], adds: List[ClauseDesignator])

object RemoveAdd {
  val nil = RemoveAdd(Nil, Nil)
}
3 Likes