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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With