我有一个函数def f(a: Int, b: Int, c: Int, d: Int, ...)
,我想在单元测试中提供一系列连续的整数作为参数。
有没有简洁的方法将(1 to N).toList
提供给f
?由于该函数不是def f(x: Int*)
,因此我不能简单地使用list: _*
,其中list
是整数列表。
我有一个函数def f(a: Int, b: Int, c: Int, d: Int, ...)
,我想在单元测试中提供一系列连续的整数作为参数。
有没有简洁的方法将(1 to N).toList
提供给f
?由于该函数不是def f(x: Int*)
,因此我不能简单地使用list: _*
,其中list
是整数列表。
import shapeless._
import shapeless.ops.function._
import shapeless.ops.traversable._
def applyToList[F, HL <: HList, R](f: F)(args: List[Any])(implicit
// convert `(T1, T2, ...) => R` to a function from a single HList argument `HL => R`
fnToProduct: FnToProduct.Aux[F, HL => R],
// convert the argument list to the HList, expected by the converted function
toHList: FromTraversable[HL]
): R = {
toHList(args) match {
case Some(hargs) => fnToProduct(f)(hargs)
case None => sys.error("argument list not applicable to function")
}
}
def f(a: Int, b: Int, c: Int, d: Int): Any = ???
applyToList(f _)(List(1, 2, 3, 4))
f _
,因为 Scala 编译器并不知道 F
是一个函数。Option[R]
,因为在编译时无法确定提供的 List
是否适合该函数。例如,参数列表可能具有不匹配的元素数量。但如果这是用于单元测试,你也可以抛出异常。f()
,那么你就有些束手无策了。你可以做一件(不是很好的)事情,写一个隐式翻译器。f()
需要4个Int
参数。implicit class Caller4[A,R](func: (A,A,A,A)=>R) {
def call(as :A*) :R = func(as(0),as(1),as(2),as(3))
}
(f _).call(1 to 4:_*) //call f(1,2,3,4)
call()
,编译器将无法捕获它。