Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is method parameter forwarding possible in Scala?

Is it possible to write something similar to:

def foo(x: Int, y: Double)

def bar(x: Int, y: Double) = foo(_)

I would like to avoid repeating myself in saying:

def foo(x: Int, y: Double)

def bar(x: Int, y: Double) = foo(x, y)

So in the case where the both parameter lists are the same in type and size and no repositioning of parameters should happen, can something like parameter forwarding achieved?

like image 350
Tim Friske Avatar asked Nov 22 '11 17:11

Tim Friske


1 Answers

Yes, if the function bar is doing nothing other than forwarding exactly on to foo, you can do the following:

def foo(x : Int, y : Double) { println("X: " x + " y: " + y) }
def bar = foo _

bar(1,3.0)
//prints out "X: 1 y: 3.0"

In this case the underscore indicates that you want to return the function foo itself, rather than calling it and returning the reuslt. This means that when bar is called, it will simply return the function foo, which will then be called with the arguments you provided.

like image 73
nonVirtualThunk Avatar answered Sep 17 '22 14:09

nonVirtualThunk