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

心已入冬 提交于 2019-12-11 07:58:13

问题


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

回答1:


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)


来源:https://stackoverflow.com/questions/52214333/is-there-a-way-to-guarantee-case-class-copy-methods-exist-with-type-classes-in-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!