简体   繁体   中英

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));
}

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

After some experimenting i have come to the conclusion that it kind of works the same way in Scala as in C# (not sure if it is actually the same though...)

This is what I was trying to achieve (playing around with Play! so Scala is new to me, not sure why this didn't work in my views, but it works fine when I try 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

You can actually simulate the behavior of method groups with partial functions. However, it's probably not a recommended approach, as you force any type errors to occur at runtime, as well as incur some cost to determine which overload to call. 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM