简体   繁体   English

是否可以为伴侣 object 指定特征?

[英]Is it possible to specify a Trait for a companion object?

Let's say I have this:假设我有这个:

trait FormData

case class DepartmentData(id: Long, title: String) extends FormData

and this companion object:和这个伴侣 object:

object DepartmentData {
  def empty: DepartmentData = ???
  def from(value: SomeKnownType): DepartmentData = ???
}

What I would like is to make sure that all the classes implementing the FormData Trait, have the two methods empty and from in their companion object.我想要确保所有实现FormData Trait 的类在它们的伴侣 object 中有两个方法为emptyfrom

I do not think we can do this directly, however try type class solution like so我不认为我们可以直接这样做,但是尝试像这样的 class解决方案

trait FormData
case class DepartmentData(id: Long, title: String) extends FormData
case class EmployeeData(id: Long, title: String) extends FormData

trait SomeKnownType

trait FormDataFactory[T <: FormData] {
  def empty: T
  def from(value: SomeKnownType): T
}

object FormDataFactory {
  def empty[T <: FormData](implicit ev: FormDataFactory[T]): T = ev.empty
  def from[T <: FormData](value: SomeKnownType)(implicit ev: FormDataFactory[T]): T = ev.from(value)

  implicit object fooDepartmentData extends FormDataFactory[DepartmentData] {
    override def empty: DepartmentData = ???
    override def from(value: SomeKnownType): DepartmentData = ???
  }

  implicit object fooEmployeeData extends FormDataFactory[EmployeeData] {
    override def empty: EmployeeData = ???
    override def from(value: SomeKnownType): EmployeeData = ???
  }
}

Now call现在打电话

FormDataFactory.empty[DepartmentData]
FormDataFactory.empty[EmployeeData]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM