Reputation: 1291
I have a method setBuildQuery
and I want that it can receive as parameter a function x
. The function x
should take as input an indefinite number of parameters and output another function y
.
Function y
takes as input two dates and outputs a string.
Examples using a function notation
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
How can I model this in Scala (i.e. how can I say to a function to accept a function x of this type?
How the user of my app can specify this function as a val
?
I was thinking something like function of function or high order functions. I am not too familiar with them in Scala though.
Upvotes: 0
Views: 762
Reputation: 8594
You can't have a function that takes an arbitrary number of parameters.* The best you could do is take a function that takes a Seq:
def setBuildQuery(f: Seq[YourType] => (Date, Date) => String)
You could then define a function it accepts like this:
val f: Seq[YourType] => (Date, Date) => String =
ls => (from, to) => ???
* You can have a method that takes an arbitrary number of parameters, but that doesn't help here.
Upvotes: 1
Reputation: 1428
There are many way to do that, you can use Partial Application to define your function.
The function will not execute until you invoke it with all its parameters
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)
or you can return a function
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)
Upvotes: 0