本文介绍了Scala函数中的异构参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何传递一些HList作为参数?所以我可以这样:

How can I pass some HList as an argument? So I can make in a such way:

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 dunno nothing about it, how can I make some operations on it?How can I pass argument and not to loose its type?

推荐答案

这取决于您的用例.

HList对于类型级别的代码很有用,因此您不仅应将HList传递给您的方法,还应传递所有必要的信息,如下所示:

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
}

例如,如果您想reverse您的Hlistmap超出结果,则应使用MapperReverse这样:

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)

用法:

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

这篇关于Scala函数中的异构参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-13 06:39