Inhomogeneous Arguments in Scala Function

How to pass part of HList as an argument? Therefore, I can do this:

 def HFunc[F, S, T](hlist: F :: S :: T :: HNil) { // here is some code } HFunc(HList(1, true, "String")) // it works perfect 

But if I have a long list and I don’t know anything about it, how can I do some operations on it? How to pass an argument and not lose its type?

+7
list scala shapeless hlist heterogeneous
source share
1 answer

It depends on your use case.

HList is useful for type type code, so you must pass your method not only to HList , but also all the necessary information:

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

For example, if you want reverse to get the result of HList and map , you should use Mapper and reverse as follows:

 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) 

Using:

 hFunc(HList(1, true, "String")) //String :: Boolean :: Int :: HNil = not String :: false :: -1 :: HNil 
+8
source share

All Articles