How can I create an array of functions in Scala so I can loop over them and call them to perform calculations?
def f1(x: Int, y: Int): Int = x + y
def f2(x: Int, y: Int): Int = x - y
def f3(x: Int, y: Int): Int = x * y
def test() {
val someValues1 = List(1, 2)
val someValues2 = List(3, 4)
val fnList = Array(f1,f2,f3)
for (f <- fnList; a <- someValues1; b <- someValues2) {
val result = f(a, b)
println("Result=" + result)
}
}
In your question, you say that you want an array of functions. But there isn’t a single function in your entire code snippet!
I’m guessing by the names
f1,f2andf3that you thought those were functions. But they aren’t: thedefkeyword is used to declare methods, not functions. Those two are fundamentally different!So, if you want to use an array of functions, just make
f1,f2andf3actually be functions instead of methods:An alternative to that would be to actually read the error message, which tells you exactly what the problem is and how to fix it:
So, if you simply do what the error message tells you to do, namely convert the methods to functions using the
_operator, everything will work fine:The reason why you are getting the error message is simply because Scala allows you to leave off the parentheses in a method call. So,
f1just means “callf1without an argument list”, which is an error, becausef1takes two arguments.In some cases, when it is really painfully blatantly obvious that the argument cannot possibly be anything but a function, Scala will perform the conversion from method to function for you automatically. So, a third option would be to make it painfully blatantly obvious to Scala that you do have an array of functions, by, you know, declaring it as an array of functions:
Now that Scala knows that
fnListis an array of functions, it no longer tries to callf1, instead it converts it to a function.