HList 作为具有简化类型签名的方法的参数

HList as parameter of method with simplified type signature

假设我有容器标记

case class TypedString[T](value: String)

其中 value 表示特定类型的一些 ID T

我有两个类

case class User(id: String)
case class Event(id: String)

我有一个函数可以做一些事情:

def func[L <: HList](l: L)(...) {...}

所以我可以像

一样使用它
func[TypedString[User] :: TypedString[Event] :: HNil](
    TypedString[User]("user id") :: TypedString[Event]("event id") :: HNil
)

(明确保留类型签名对我来说很重要)

问题是:如何更改或扩展 func 以具有更短的类型签名(仅保留标记类型),例如:

func[User :: Event :: HNil](
    TypedString[User]("user id") :: TypedString[Event]("event id") :: HNil
)

shapeless.ops.hlist.Mapped 类型 class 给出了一个 HList L 和另一个 HList 的关系,其中 L 的元素被包装在类型构造函数中。

因为你现在有两种类型,你要指定的类型L和另一种类型(L的元素包裹在TypedString中),我们需要使用相同的我们在 中使用的技巧(当时因为我们不想一次提供所有参数,现在因为我们只想指定第一种类型)。

import shapeless._
import ops.hlist.Mapped

def func[L <: HList] = new PartFunc[L]

class PartFunc[L <: HList] {
  def apply[M <: HList](m: M)(implicit mapped: Mapped.Aux[L, TypedString, M]): M = m
}

现在您可以随意使用 func 了:

func[User :: Event :: HNil](
    TypedString[User]("user id") :: TypedString[Event]("event id") :: HNil
)
// TypedString[User] :: TypedString[Event] :: HNil =
//     TypedString(user id) :: TypedString(event id) :: HNil