在Scala中对案例类应用递归操作

时间:2019-05-02 16:06:14

标签: scala typeclass shapeless

我正在尝试找到一种优雅的方法来进行以下操作。

让我们假设有下面的类:

case class Foo(fooName: String, bar: Bar, baz: Baz)
case class Bar(barName: String, baz: Baz)
case class Baz(bazName: String)

例如,我希望能够更改名称(在Foo及其子对象的情况下以某种方式),以便为它们添加一些标题。

我可以定义一个用于该目的的类型类:

trait Titled[T] {
  def titled(t: T)(title: String): T
}

对于Foo,实现将执行以下操作:

implicit val fooTitled: Titled[Foo] = new Titled[Foo] {
  def titled(foo: Foo)(title: String): Foo = foo.copy(fooName = title + fooName)
}

可能还有其他实现,例如Esquired,将在名称后加上“ Esq”。

但是,这不会更新我想要的子值,bar和baz的标题。

我最终想要得到的是这样的东西:

//import all the implicits needed
val foo = Foo(...)
val titledFoo = foo.title("Mr. ") // names are prefixed with Mr.
val andEsquired = foo.esquire // names are also suffixed with Esq

现在,我一直在网上寻找是否可行,并且我看到了无形库,但是我仍然不具备我可以破译和创建这种“魔术”的Scala知识水平。如果可能的话。

我不一定要寻找一个完整的解决方案(尽管我会很感激),但是如果有人可以向我指出正确的方向,向我展示一些示例,教程或类似的东西,我将非常感激

1 个答案:

答案 0 :(得分:1)

尝试以下类型类。我假设所有应该具有类实例的案例类都具有要前缀的String类型的第一个字段。

  import shapeless.ops.hlist.IsHCons
  import shapeless.{::, Generic, HList, HNil}

  trait Titled[T] {
    def titled(t: T)(title: String): T
  }

  object Titled {
    //implicit def identity[A]: Titled[A] = new Titled[A] {
    //  override def titled(t: A)(title: String): A = t
    //}

    implicit def transform[A <: Product, L <: HList, H, T <: HList](implicit
      generic: Generic.Aux[A, L],
      isHCons: IsHCons.Aux[L, String, T],
      tailTitled: HListTitled[T]): Titled[A] = new Titled[A] {
      override def titled(t: A)(title: String): A = {
        val l = generic.to(t)
        val head = isHCons.head(l)
        val tail = isHCons.tail(l)
        val newHead = title + head
        val newTail = tailTitled.titled(tail)(title)
        val newL = isHCons.cons(newHead, newTail)
        generic.from(newL)
      }
    }
  }

  trait HListTitled[L <: HList] {
    def titled(t: L)(title: String): L
  }

  object HListTitled {
    implicit val hnil: HListTitled[HNil] = new HListTitled[HNil] {
      override def titled(t: HNil)(title: String): HNil = HNil
    }

    implicit def hcons[H, T <: HList](implicit
      headTitled: Titled[H],
      tailTitled: HListTitled[T]): HListTitled[H :: T] = new HListTitled[H :: T] {
      override def titled(t: H :: T)(title: String): H :: T = 
        headTitled.titled(t.head)(title) :: tailTitled.titled(t.tail)(title)
    }
  }

  implicit class TitledOps[T](t: T) {
    def titled(title: String)(implicit ttld: Titled[T]): T = ttld.titled(t)(title)
  }

  case class Foo(fooName: String, bar: Bar, baz: Baz)
  case class Bar(barName: String, baz: Baz)
  case class Baz(bazName: String)
  case class Foo1(fooName: String, bar: Bar, baz: Baz, i: Int)

  Foo("Johnson", Bar("Smith", Baz("Doe")), Baz("James")).titled("Mr. ")
  // Foo(Mr. Johnson,Bar(Mr. Smith,Baz(Mr. Doe)),Baz(Mr. James))
  Foo1("Johnson", Bar("Smith", Baz("Doe")), Baz("James"), 10).titled("Mr. ")
  // doesn't compile
  // if you want it to compile uncomment "identity"