简体   繁体   中英

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 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.

I do not think we can do this directly, however try type class solution like so

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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