【发布时间】:2021-02-28 04:20:26
【问题描述】:
我发现我的代码经常看起来像这样:
trait Example {
def getThing1[A, O <: HList](a: A)(implicit g1: GetThing1[A] { type Out = O }): O = g1(a)
def getThing2[A, O <: HList](a: A)(implicit g2: GetThing2[A] { type Out = O }): O = g2(a)
def combineThings[T1 <: HList, T2 <: HList, O <: HList](t1: T1, t2: T2)(implicit
c: CombineThings[T1, T2] {type Out = O},
): O = c(t1, t2)
def getCombinedReversed[A, T1 <: HList, T2 <: HList, C <: HList, O <: HList](a: A)(implicit
g1: GetThing1[A] {type Out = T1},
g2: GetThing2[A] {type Out = T2},
c: CombineThings[T1, T2] {type Out = C},
r: Reverse[C] {type Out = O},
): O = r(combineThings(getThing1(a), getThing2(a)))
}
这实际上比仅使用隐式而不调用getThing1、getThing2 或combineThings 方法的独立getCombinedReversed 方法更复杂:
def getCombinedReversedStandAlone[A, T1 <: HList, T2 <: HList, C <: HList, O <: HList](a: A)(implicit
g1: GetThing1[A] {type Out = T1},
g2: GetThing2[A] {type Out = T2},
c: CombineThings[T1, T2] {type Out = C},
r: Reverse[C] {type Out = O},
): O = r(c(g1(a), g2(a)))
我对此没有什么特别的问题,但它确实使我的代码有点膨胀,所以我想我会检查一下是否没有明显的解决方案。显然,调用 getThing 和 combineThings 方法而不断言正确的隐式在范围内是不可能的。
感谢您的帮助。
【问题讨论】:
标签: scala typeclass implicit shapeless boilerplate