在Scala中将函数的功能作为参数传递

时间:2018-08-09 16:24:18

标签: scala functional-programming

我有一个方法setBuildQuery,我希望它可以将函数x作为参数接收。函数x应将不确定数量的参数作为输入,并输出另一个函数y。 函数y将两个日期作为输入并输出一个字符串。

使用功能符号的示例

x = (one_f)(from_date, to_date) => string                      or
x = (one_f, two_f)(from_date, to_date) => string               or
x = (one_f, two_f, ..., n_f)(from_date, to_date) => string

如何在Scala中对此建模(即,如何对一个函数说服这种类型的函数x? 我的应用程序的用户如何将该功能指定为val

我在想类似函数函数或高阶函数的东西。我在Scala中对它们不太熟悉。

2 个答案:

答案 0 :(得分:1)

您不能有一个带有任意数量参数的函数。*最好的办法是带有一个Seq的函数:

def setBuildQuery(f: Seq[YourType] => (Date, Date) => String)

然后您可以定义一个可以接受的函数,如下所示:

val f: Seq[YourType] => (Date, Date) => String =
    ls => (from, to) => ???

*您可以有一个采用任意数量参数的方法,但这在这里无济于事。

答案 1 :(得分:0)

有很多方法可以执行此操作,您可以使用“部分应用程序”来定义函数。

该函数只有在使用所有参数调用后才会执行

def x(head:String, tail:String*)(from:Date, to:Date): String = {
  println(head) // it doesnt exec until from and to are provided
  "result"
}

val y = x("string1", "string2") _

y(new Date, new Date)

或者您可以返回一个函数

def x(head:String, tail:String*): (Date,Date) => String = {
  println(head) // it exec before from and to are provided
  (from:Date, to:Date) => {
    "result"
  }
}

val y = x("string1", "string2")

y(new Date, new Date) 
相关问题