我想做一些非常简单的事情,但我正在努力制定正确的搜索或只是理解我见过的一些解决方案。
给定一个采用泛型类型参数的方法,该参数是Coproduct;
def apply[T <: Coproduct] = {
...
}
如何迭代构成副产品的类型?具体来说,对于作为案例类的每种类型,我想递归检查每个字段并构建包含所有信息的地图。
目前我正在使用构建器模式解决此问题,我将在此处发布以防其他人使用;
class ThingMaker[Entities <: Coproduct] private {
def doThings(item: Entities): Set[Fact] = {
...
}
def register[A <: Product with Serializable]: ThingMaker[A :+: Entities] = {
// useful work can be done here on a per type basis
new ThingMaker[A :+: Entities]
}
}
object ThingMaker {
def register[A <: Product with Serializable]: ThingMaker[A :+: CNil] = {
// useful work can be done here on a per type basis
new ThingMaker[A :+: CNil]
}
}
答案 0 :(得分:3)
如果您只想检查值,您可以简单地在副产品上进行模式匹配,就像任何其他值一样...
def apply[T <: Coproduct](co: T): Any = co match {
case Inl(MyCaseClass(a, b, c)) => ???
...
}
...但是如果你想比这更精确,例如要有一个取决于输入的返回类型,或者检查这个副产品中的类型来召唤暗示,那么你可以写完全相同的模式匹配表达式使用类型类和几个隐式定义:
trait MyFunction[T <: Coproduct] {
type Out
def apply(co: T): Out
}
object MyFunction {
// case Inl(MyCaseClass(a, b, c)) =>
implicit val case1 = new MyFunction[Inl[MyCaseClass]] {
type Out = Nothing
def apply(co: Inl[MyCaseClass]): Out = ???
}
// ...
}
通常,当您希望遍历所有类型的副产品时,您将始终遵循相同的尾递归结构。作为一个功能:
def iterate[T <: Coproduct](co: T): Any = co match {
case Inr(head: Any) => println(v)
case Inl(tail: Coproduct) => iterate(tail)
case CNil => ???
}
或作为“依赖类型函数”:
trait Iterate[T <: Coproduct]
object Iterate {
implicit def caseCNil = new Iterate[CNil] {...}
implicit def caseCCons[H, T <: Coproduct](implicit rec: Iterate[T]) =
new Iterate[H :+: T] {...}
}
例如,您可以使用隐式附加ClassTag
来获取副产品中每种类型的名称:
trait Iterate[T <: Coproduct] { def types: List[String] }
object Iterate {
implicit def caseCNil = new Iterate[CNil] {
def types: List[String] = Nil
}
implicit def caseCCons[H, T <: Coproduct]
(implicit
rec: Iterate[T],
ct: reflect.ClassTag[H]
) =
new Iterate[H :+: T] {
def types: List[String] = ct.runtimeClass.getName :: rec.types
}
}
implicitly[Iterate[Int :+: String :+: CNil]].types // List(int, java.lang.String)
由于Scala允许您影响隐式优先级的方式,实际上可以将具有模式匹配的任何递归函数转换为此“依赖类型函数”模式。这与Haskell不同,只有在匹配表达式的调用情况可证明不重叠时才能写入此函数。