探索 shapeless 的“最后一个”类型 Class

Explore shapeless's `Last` Type Class

我或多或少地输入了 shapelessLastLast 类型 class:

import shapeless.{HList, HNil, ::}

trait Last[H <: HList] {
  type Out
  def last(in: H): Out
}

然后,据我所知,输入 class 实例 Last for HList:

object Last {
  type Aux[L <: HList, O] = Last[L] { type Out = O }

  // arrived at the truly `last` item, i.e. `H`
  implicit def singleLast[H]: Aux[H :: HNil, H] = new Last[H :: HNil] {
    override type Out = H
    override def last(in: H :: HNil): H = in.head
  }

  // I believe this is the inductive step
  implicit def hlistLast[H, T <: HList, OutT]
  (implicit lt : Last.Aux[T, OutT]): Aux[H :: T, OutT] =
    new Last[H :: T] {
      type Out = OutT
      def apply(l : H :: T): Out = lt(l.tail)
    }
}

但是,我不明白为什么编译失败:

[error] /Users/kevinmeredith/Workspace/shapeless-sandbox/src/
      main/scala/net/ops.scala:17: net.Last.Aux[T,OutT] does not take parameters
[error]       def apply(l : H :: T): Out = lt(l.tail)
[error]                                      ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed

如何修复此编译时错误?

Last 的实际无形实现如下所示:

trait Last[H <: HList] {
  type Out
  def apply(in: H): Out
}

您将 apply 更改为 last,但在 hlistLast 中您仍在尝试使用 apply(通过定义它并在 [=17= 上使用它) ]):

def apply(l : H :: T): Out = lt(l.tail)

编译器错误来自尝试使用不存在的 lt.apply。如果编译器首先告诉您 last 未实现,在这种情况下会更有帮助。