我总是按照应有的方式使用伴生对象:具有某些类或特征,我在同一文件中定义了具有相同类名的对象。 但我目前正在尝试提取一些很少有伴生对象共享的常见功能,并想知道拥有这样的东西是否安全:
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"))
}
我不确定案例类伴生对象扩展某些其他特征是否安全。它编译并运行良好,但很高兴听到一些意见。
最佳答案
当然可以,就像非伴生对象
一样。这实际上是将“静态”表示为伴随对象的主要优点之一。扩展类而不是特征也是有效的。
您可以在集合伴生对象扩展的标准库中看到它 GenericCompanion
及其各种亚型。
关于scala - 伴生对象可以扩展一些与伴生类不同的特征吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48987963/