scala宏如何将`HList`转换为函数args

时间:2018-02-28 03:30:52

标签: scala shapeless scala-macros

以下类型

type HFunc = (Int :: String :: HNil) => Int

type Func = (Int, String) => Int

我尝试将Func转换为HFunc

val funExpr: Tree = ???
val hlistType = ???      
val hfuncName = c.freshName("hfunc")

q"""
  def $hfuncName(t: $hlistType) = {
    ${funExpr}(..) //how to extract hlist elements as params ?
  }
"""

如何提取HList元素并将其传递给Func

1 个答案:

答案 0 :(得分:2)

如果你想要的只是转换(而不一定是宏),那么shapeless提供了开箱即用的功能扩展方法:

import shapeless._
import shapeless.syntax.std.function._

type HFunc = (Int :: String :: HNil) => Int
type Func = (Int, String) => Int

def toHFunc(f: Func): HFunc = f.toProduct
def fromHFunc(hf: HFunc): Func = hf.fromProduct