如何用HList调用多个参数的函数?

Mic*_*ael 4 scala shapeless

假设我有一个HList类型A::B::C::HNil和一个函数(A, B, C) => D

val hlist: A::B::C::HNil = ???
def foo(a: A, b: B, c: C): D = ???
Run Code Online (Sandbox Code Playgroud)

现在我需要一个功能可按A::B::C::HNil => D,它使用foo返回D.

def bar(hslist: A::B::C::HNil): D = ???
Run Code Online (Sandbox Code Playgroud)

你会如何实施bar

Tra*_*own 9

为此,您可以多一点利用直接无形的FnToProduct,它提供toProduct了转换的语法FunctionNFunction1服用HList:

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

type A = String
type B = Symbol
type C = Int
type D = List[String]

val hlist: A :: B :: C :: HNil = "foo" :: 'x :: 1 :: HNil

def foo(a: A, b: B, c: C): D = List.fill(c)(a + b)

def bar(hslist: A :: B :: C :: HNil): D = (foo _).toProduct.apply(hslist)
Run Code Online (Sandbox Code Playgroud)

在许多情况下,您可能甚至不想要单独的bar定义.