假设我有一个 HList
类型 A::B::C::HNil
和一个函数 (A, B, C) => D
val hlist: A::B::C::HNil = ???
def foo(a: A, b: B, c: C): D = ???
现在我需要一个函数
A::B::C::HNil => D
, 使用 foo
返回 D
.def bar(hslist: A::B::C::HNil): D = ???
您将如何实现
bar
?
最佳答案
您可以使用 Shapeless 的 FnToProduct
更直接地执行此操作。 ,提供 toProduct
转换 FunctionN
的语法成Function1
服用 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)
在许多情况下,您甚至可能不需要单独的
bar
定义。
关于scala - 如何使用 HList 调用多个参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31588877/