Is method parameter transfer 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 not to repeat, saying:

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

So, in the case when both lists of parameters are the same in type and size, and there is no permutation of the parameters, can something like redirecting the parameters?

+4
source share
2 answers

Yes, if the function panel does nothing but send it exactly 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 yourself, instead of calling it and returning it again. This means that when bar is called, it simply returns the function foo , which will then be called with the arguments you provide.

+10
source

Yeah but it's a little pun

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

In this case, bar is not a method that accepts int and double. Instead, the method takes no arguments, returning the function that takes, and int a double. From the perspective of the caller, they can be used interchangeably.

 bar(3, 5.9) // expands to bar apply(3, 5.9), which calls foo 
+3
source

Source: https://habr.com/ru/post/1382536/


All Articles