abdolence
abdolence

Reputation: 2416

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?

Upvotes: 3

Views: 535

Answers (2)

cocteau
cocteau

Reputation: 31

To expand on @Jens' answer, with the same idea you can add more than 1 parameter:

scala> def somefunc( arg1 : String, arg2: String ) = {println(arg1 + arg2)}
def test[X,Y,Z]( f : (X,Y) => Z) = f
test( somefunc )("foo", "bar")

output:

somefunc: (arg1: String, arg2: String)Unit

scala> test: [X, Y, Z](f: (X, Y) => Z)(X, Y) => Z

scala> foobar

Upvotes: 0

Jens
Jens

Reputation: 9406

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 )
}

Upvotes: 1

Related Questions