如何通過一些HList
作爲參數?因此,我可以做一個這樣的方式:Scala函數中的異構參數
def HFunc[F, S, T](hlist: F :: S :: T :: HNil) {
// here is some code
}
HFunc(HList(1, true, "String")) // it works perfect
但是,如果我有一個長長的清單,我不知道一無所知,我怎麼能做出一些關於它的操作? 我怎樣才能通過爭論而不是放棄它的類型?
如何通過一些HList
作爲參數?因此,我可以做一個這樣的方式:Scala函數中的異構參數
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
y我看到,例如:'def hFunc [L <:HList](hlist:L)(implicit m: TypeTag [L])'並且'm'中有關於對象類型的所有信息;但我不能使'hlist.head',因爲實際上'hlist'參數有另一種類型;它會拋出一個錯誤(製作'hlist.head'):'找不到參數c的隱式值:shapeless.IsHCons [L]' – DaunnC
@DaunnC:不是'TypeTag'。你應該使用'Mapper'作爲'map','Reverse'作''reverse''等等。 – senia
w0w thx!我會盡力;你有一些鏈接讓我學習? – DaunnC
你想在方法體中執行什麼樣的操作? –
hm,某些類型依賴對象可以存儲在這個列表中,我不想丟失關於對象類型的信息。所以我需要mb在'HLists' - 'map,head等''上的所有操作...... :) – DaunnC