Heterogeneous arguments in a Scala function

与世无争的帅哥 提交于 2019-11-30 14:01:01

It depends on your use-case.

HList is useful for type-level code, so you should pass to your method not only HList, but also all necessary information like this:

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

For instance if you want to reverse your Hlist and map over result you should use Mapper and Reverse like this:

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)

Usage:

hFunc(HList(1, true, "String"))
//String :: Boolean :: Int :: HNil = not String :: false :: -1 :: HNil
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!