将一个 HList 隐式转换为另一个

implicit conversion of one HList to another

我的库中有一个用例,如果 包含 HList B 的所有元素,则认为 HList A 可转换为 HList B ] 不管 排序。我需要在两者之间进行隐式转换,例如:

// implicit arguments omitted for readability
implicit def toOther[A <: HList, B <: HList](l: A): B = l.filter[B].align[B]

HList.filter returns HNil 如果提供了类型为 HList 的类型参数。我还能如何将 A 转换为 B?

编辑

这是实现该功能的尝试如果您需要样板来复制和粘贴:

import shapeless.{::, HList, HNil}
import shapeless.ops.hlist.Align

implicit def toOther[A <: HList, B <: HList](v: A)(implicit a: Align[A, B]): B = v.align[B]

def method(p: Int :: Boolean :: HNil): Unit = println("success")

val list = false :: 7 :: HNil

// works on it's own. (only for Hlists of same length though)
toOther[Boolean :: Int :: HNil,Int :: Boolean :: HNil](list)

//doesn't work! Weird!
// also if it did, it only would for two HLists of the same length
method(list)

对于转换部分,我认为您正在寻找的是 SelectAll 类型类。至于为什么转换没有隐式启动,我还不确定。似乎在您的示例中预期类型和实际类型都已知的情况下,编译器有足够的信息来选择 toOther.

import shapeless._, ops.hlist.SelectAll

implicit def toOther[A <: HList, B <: HList](a: A)(implicit convert: SelectAll[A,B]): B = convert(a)