合并HList元素

时间:2017-04-28 16:35:44

标签: scala shapeless hlist

我有一个简单的服务定义

trait Service[-Req, +Rep] extends (Req => Future[Rep]) {
    def apply(request: Req): Future[Rep]
}

以及如何连接服务的方法:

implicit class ServiceOps1[Req, RepIn](service: Service[Req, RepIn]) {
    def -->[RepOut](next: Service[RepIn, RepOut]): Service[Req, RepOut] =
        (req: Req) => service(req) flatMap next
}

我想将我的所有服务(假设可以编写)放入HList,然后从HList构建服务组合。

这是我的Resolver

  trait Resolver[L <: HList, In] {
    type Out
    def apply(l: L): Service[In, Out]
  }

  object Resolver {
    def apply[L <: HList, In](implicit resolver: Resolver[L, In]): Aux[L, In, resolver.Out] = resolver

    type Aux[L <: HList, In, Out0] = Resolver[L, In] { type Out = Out0 }

    implicit def hsingleResolver[I, O, S <: Service[I, O]]: Aux[S :: HNil, I, O] =
      new Resolver[S :: HNil, I] {
        type Out = O
        def apply(l : S :: HNil): Service[I, Out] = l.head
      }

    implicit def hlistResolver[I, O, S <: Service[I, O], T <: HList](implicit res : Resolver[T, O]): Aux[S :: T, I, res.Out] =
      new Resolver[S :: T, I] {
        type Out = res.Out

        def apply(l: S :: T): Service[I, res.Out] = l.head --> res(l.tail)
      }
  }

我有服务

object S extends Service[Int, String] {
    def apply(request: Int): Future[String] =  Future successful request.toString
}

当我尝试解决简单链

implicitly[Resolver[S.type :: HNil, Int]].apply(S :: HNil)

我收到了一个隐含的未找到错误。

2 个答案:

答案 0 :(得分:1)

不知道为什么这会被投票,也许你可以提供样品回购。无论如何,这是一个部分答案,也许这让你回到正轨。

1)为build.sbt中的implicits启用调试选项:implicit def hNilResolver[I]: Aux[HNil, I, HNil] = ???

2)为HNil定义一个解析器:foreach ($emails as $key => $email) { echo $email; echo $firstnames[$key]; echo $lastnames[$key]; }

3)在调试输出之后,修复余数:)

答案 1 :(得分:1)

问题在于你的隐含的类型签名:implicit def hsingleResolver[I, O, S <: Service[I, O]]: Aux[S :: HNil, I, O]。这是因为S <: Service[I, O]您希望根据O的类型推断S,但不幸的是,它不是如何运作的。推断类型参数时,不考虑类型参数列表中的S <: Service[I, O]子句。调用implicitly[Resolver[S.type :: HNil, Int]]时会发生什么,编译器发现S = S.typeI = IntO未知,因此O = Nothing。然后继续检查S <: Service[Int,Nothing]是否为假,隐式搜索失败。

因此,要解决此问题,您必须将S <: Service[I, O]部分隐式搜索/类型推断过程作为事实。例如,以下列方式之一:

implicit def hsingleResolver[I, O, S](implicit ev: S <:< Service[I,O]): Aux[S :: HNil, I, O] // option 1
implicit def hsingleResolver[I, O, S]: Aux[(S with Service[I,O]) :: HNil, I, O] // option 2

作为旁注:以下列方式定义Resolver会更有意义吗?

trait Resolver[L <: HList] {
  type In
  type Out
  def apply(l: L): Service[In, Out]
}

object Resolver {
  def apply[L <: HList](implicit resolver: Resolver[L]): Aux[L, resolver.In, resolver.Out] = resolver

  type Aux[L <: HList, In0, Out0] = Resolver[L] { type In = In0; type Out = Out0 }

  ...
}

因为In也依赖于L,就像Out一样。