是否可以为伴随对象指定特征?

时间:2019-10-01 17:05:30

标签: scala

假设我有这个:

trait FormData

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

和此伴随对象:

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

我要确保所有实现FormData特性的类在其伴随对象中都具有两个方法emptyfrom

1 个答案:

答案 0 :(得分:2)

我认为我们不能直接做到这一点,但是请尝试像这样的 type 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 = ???
  }
}

现在通话

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