Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function reference with any arguments to another function in Scala

What is the best way to pass a function reference in Scala to another function in cases you don't know the function arguments (e.g. you would like to use reflection on it etc)?

I'm trying to define something like this:

def test(f: (Any*) => Any) = ... // Any implementation 

and call it with like:

def somefunc( arg1 : String, arg2 : Int, ... ) = {} // Any function with any arguments
test(somefunc) // Pass the reference to the function

Is it possible to do at all?

like image 360
abdolence Avatar asked May 13 '26 09:05

abdolence


1 Answers

It depends on what you want to do with the function later on. A simple solution would be to use generics:

def somefunc( arg1 : String ) = {} // Any function with any arguments
def test[X,Y]( f : X => Y) = f

def main(args: Array[String]) {
    test( somefunc )
}
like image 158
Jens Avatar answered May 16 '26 04:05

Jens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!