简体   繁体   中英

Is there a way to guarantee case class copy methods exist with type classes in Scala?

In the example below I have a type class Foo , and would like to somehow guarantee that all members conforming to Foo (such as Bar via barFoo ) have a copy method such as the one generated by way of being a case class . I haven't thought of a way to do this. In this case the copy signature would be possibly be something like copy(foo: F, aa: List[T] = foo.aa, maybe: Option[T] = foo.maybe): F .

trait Foo[F] {
  type T
  def aa(foo: F): List[T]
  def maybe(foo: F): Option[T]
}

final case class Bar(aa: List[String], maybe: Option[String])
object Bar {
  implicit val barFoo = new Foo[Bar] {
    type T = String
    def aa(foo: Bar): List[String] = foo.aa
    def maybe(foo: Bar): Option[T] = foo.maybe
  }
}

I couldn't do it with type member, but here you are a version with type parameters. Also it is necessary to add a method to Foo to construct the object.

trait Foo[F, T] {
  def aa(foo: F): List[T]
  def maybe(foo: F): Option[T]
  def instance(aa: List[T], maybe: Option[T]): F
}

class Bar(val aa: List[String], val maybe: Option[String]) {
  override def toString = s"Bar($aa, $maybe)"
}

object Bar {
  implicit val barFoo = new Foo[Bar, String] {
    def aa(foo: Bar): List[String] = foo.aa
    def maybe(foo: Bar): Option[String] = foo.maybe
    def instance(aa: List[String], maybe:Option[String]):Bar = new Bar(aa, maybe)
  }
}

implicit class FooOps[A, T](fooable:A)(implicit foo:Foo[A, T]) {

  def copy(aa: List[T] = foo.aa(fooable), maybe: Option[T] = foo.maybe(fooable)) = {
    foo.instance(aa, maybe)
  }

}

val r = new Bar(List(""), Option("")).copy(aa = List("asd"))

println(r)

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