Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of C# method groups in Scala?

In C# there is this very convenient thing called method groups, basically instead of writing:

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

you can write:

someset.Select(DoSomething)

is there something similar in Scala?

For example:

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));
}
like image 376
Peter Moberg Avatar asked Dec 20 '22 18:12

Peter Moberg


1 Answers

In scala we call that a 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 you are calling, in this case map. So for example in scala you can simply 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
like image 112
drexin Avatar answered Dec 30 '22 09:12

drexin