首页 > 解决方案 > 在相同形状的两个案例类之间进行一般转换

问题描述

我有一堆案例类,它们在其他密封特征中具有相同形状的对应物(每个密封特征都用于 Akka Typed 行为中的详尽模式匹配),我想从一个版本转换为具有最少样板的下一个版本。

特征看起来像这样:

object RoutingCommands {
  sealed trait Command
  final case class ProtocolMsg(name: String, id: Int) extends Command
}

object ProtocolCommands {
  sealed trait Command
  final case class ProtocolMsg(name: String, id: Int) extends Command
}

我知道我可以shapeless.Generic像这样进行转换:

val msg1 = ProtocolCommands.ProtocolMsg("foo", 1)
val msg2 = Generic[RoutingCommands.ProtocolMsg].from(
  Generic[ProtocolCommands.ProtocolMsg].to(msg1)
)

但是对于每次转换都必须这样做,而不仅仅是手动构建案例类。理想情况下,我想要一个转换器,它可以根据编译时提供的两种类型派生上述代码,例如val msg2 = convert(msg1)

作为迈出的一步,我试图将其分解为:

def convert[A,B](a: A): B = Generic[B].from(
  Generic[A].to(a)
)

但这会导致:

Error:(55, 44) could not find implicit value for parameter gen: shapeless.Generic[B]

从四处挖掘,似乎我需要使用Generic.Auxwhich 导致我:

def convert[A, B, HL <: HList](a: A)(
  implicit
  genA: Generic.Aux[A, HL],
  genB: Generic.Aux[B, HL]
) = genB.from(genA.to(a))

其中,当调用:

val msg3 = convert(msg2)

结果是:

Error:(61, 57) could not find implicit value for parameter genB: shapeless.Generic.Aux[B,HL]

这是可以理解的,因为没有定义返回类型。但是,我想出了如何提供暗示什么BgenB可以隐式推导的。

标签: scalashapelesscase-class

解决方案


您可以使用“部分应用程序”

def convert[A, HL <: HList](a: A)(
  implicit
  genA: Generic.Aux[A, HL]
) = new Helper(a, genA)

class Helper[A, HL <: HList](a: A, genA: Generic.Aux[A, HL]) {
  def apply[B](implicit genB: Generic.Aux[B, HL]) = genB.from(genA.to(a))
}

val msg3 = convert(msg2).apply[ProtocolCommands.ProtocolMsg]

(最好使用@Ben 回答中的“部分应用程序”)

或创建一个类型类

trait Convert[A, B] {
  def apply(a: A): B
}

object Convert {
  implicit def mkConvert[A, B, HL <: HList](implicit
    genA: Generic.Aux[A, HL],
    genB: Generic.Aux[B, HL]
  ): Convert[A, B] = a => genB.from(genA.to(a))
}

implicit class ConvertOps[A](a: A) {
  def convert[B](implicit cnv: Convert[A, B]): B = cnv(a)
}

val msg3 = msg2.convert[ProtocolCommands.ProtocolMsg]

https://books.underscore.io/shapeless-guide/shapeless-guide.html#sec:ops:migration “6.3 案例研究:案例类迁移”


推荐阅读