Reputation: 3425
I've always used companion objects just as they should be: having some class or trait, I've defined the object with the same class name in the same file. But I'm trying at the moment to factor out some common functionality that few companion objects share and wonder if it is safe to have something like this:
trait Label {
def label: String
}
trait InstancesMap[T <: Label] {
private var instances = Map.empty[String, T]
def init(instance: T): T = {
instances += (instance.label -> instance)
instance
}
def byLabel(label: String): T = instances(label)
}
case class EventStatus(label: String) extends Label
object EventStatus extends InstancesMap[EventStatus] {
val DRAFT = init(EventStatus("draft"))
val PUBLISHED = init(EventStatus("published"))
}
I am not sure if it is safe for case class companion object to extend some other trait. It compiles and works fine, but would be great to hear some opinions.
Upvotes: 2
Views: 1513
Reputation: 170745
Of course it can, just like non-companion object
s. That's actually one of the major advantages of representing "statics" as companion objects. Extending a class instead of a trait works too.
You can see it in the standard library where collection companion objects extend GenericCompanion
and its various subtypes.
Upvotes: 4