Scala函数中的异构参数

Dau*_*nnC 7 scala list heterogeneous hlist shapeless

我如何通过一些HList作为参数?所以我可以这样做:

def HFunc[F, S, T](hlist: F :: S :: T :: HNil) {
    // here is some code
}

HFunc(HList(1, true, "String")) // it works perfect
Run Code Online (Sandbox Code Playgroud)

但是,如果我有一个很长的清单,我不知道它,我怎么能对它做一些操作?我如何通过论证而不是松散其类型?

sen*_*nia 8

这取决于你的用例.

HList对于类型级代码很有用,所以你不仅要传递给你的方法HList,还要传递所有必要的信息:

def hFunc[L <: HList](hlist: L)(implicit h1: Helper1[L], h2: Helper2[L]) {
    // here is some code
}
Run Code Online (Sandbox Code Playgroud)

例如,如果你想reverse 你的Hlist,并map在导致你应该使用MapperReverse这样的:

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)
Run Code Online (Sandbox Code Playgroud)

用法:

hFunc(HList(1, true, "String"))
//String :: Boolean :: Int :: HNil = not String :: false :: -1 :: HNil
Run Code Online (Sandbox Code Playgroud)

  • @DaunnC:我猜[shapeless](https://github.com/milessabin/shapeless)源码,示例和测试都是最好的学习资源.您还可以阅读stackoverflow [问题](http://stackoverflow.com/questions/tagged/shapeless?sort=votes&pageSize=50).我不知道其他有用的链接.有关代码示例,请参阅我的答案中的更新 (2认同)