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

问题描述 投票:0回答:1

假设我有这个:

trait FormData

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

和此伴随对象:

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

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

scala
1个回答
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]
© www.soinside.com 2019 - 2024. All rights reserved.