What is equivalent to C # method groups in Scala?

C # has a very convenient thing called method groups, mainly instead of writing:

someset.Select((x,y) => DoSomething(x,y)) 

You can write:

 someset.Select(DoSomething) 

is there something similar in Scala?

For instance:

 int DoSomething(int x, int y) { return x + y; } int SomethingElse(int x, Func<int,int,int> f) { return x + f(1,2); } void Main() { Console.WriteLine(SomethingElse(5, DoSomething)); } 
+4
source share
3 answers

In scala, we call the function ;-). (x,y) => DoSomething(x,y) is an anonymous function or closure, but you can pass any function that matches the signature of the method / function that you are calling, in this case map . So, for example, in scala you can just write

 List(1,2,3,4).foreach(println) 

or

 case class Foo(x: Int) List(1,2,3,4).map(Foo) // here Foo.apply(_) will be called 
+10
source

After some experimentation, I came to the conclusion that it works the same in Scala as in C # (not sure if it is actually the same though ...)

This is what I was trying to achieve (play with Play! So Scala is new to me, not sure why it didn’t work in my views, but works fine when I try to use it in the interpreter)

 def DoStuff(a: Int, b : Int) = a + b def SomethingElse(x: Int, f (a : Int, b: Int) => Int)) = f(1,2) + x SomethingElse(5, DoStuff) res1: Int = 8 
+1
source

In fact, you can model the behavior of groups of methods with partial functions. However, this is probably not recommended because you are causing some type of error at run time, and also incur some costs to determine which congestion needs to be caused. However, does this code do what you want?

 object MethodGroup extends App { //The return type of "String" was chosen here for illustration //purposes only. Could be any type. val DoSomething: Any => String = { case () => "Do something was called with no args" case (x: Int) => "Do something was called with " + x case (x: Int, y: Int) => "Do something was called with " + (x, y) } //Prints "Do something was called with no args" println(DoSomething()) //Prints "Do something was called with 10" println(DoSomething(10)) //Prints "Do something was called with (10, -7)" println(DoSomething(10,-7)) val x = Set((), 13, (20, 9232)) //Prints the following... (may be in a different order for you) //Do something was called with no args //Do something was called with 13 //Do something was called with (20, 9232) x.map(DoSomething).foreach(println) } 
0
source

All Articles