我怎样才能通过一些 HList
作为论据?所以我可以这样制作:
def HFunc[F, S, T](hlist: F :: S :: T :: HNil) {
// here is some code
}
HFunc(HList(1, true, "String")) // it works perfect
但是如果我有一个很长的列表,我什么都不知道,我如何对其进行一些操作?
如何传递参数而不是丢失其类型?
最佳答案
这取决于您的用例。HList
对类型级代码很有用,所以你不仅应该传递给你的方法 HList
,还有所有必要的信息,如下所示:
def hFunc[L <: HList](hlist: L)(implicit h1: Helper1[L], h2: Helper2[L]) {
// here is some code
}
例如,如果您想
reverse
您的 Hlist
和 map
超过结果你应该使用 Mapper
和 Reverse
像这样:import shapeless._, shapeless.ops.hlist.{Reverse, Mapper}
object negate extends Poly1 {
implicit def caseInt = at[Int]{i => -i}
implicit def caseBool = at[Boolean]{b => !b}
implicit def caseString = at[String]{s => "not " + s}
}
def hFunc[L <: HList, Rev <: HList](hlist: L)(
implicit rev: Reverse[L]{ type Out = Rev },
map: Mapper[negate.type, Rev]): map.Out =
map(rev(hlist)) // or hlist.reverse.map(negate)
用法:
hFunc(HList(1, true, "String"))
//String :: Boolean :: Int :: HNil = not String :: false :: -1 :: HNil
关于list - Scala 函数中的异构参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19634394/