4

在 C# 中有一个非常方便的东西叫做方法组,基本上不用写:

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

你可以写:

someset.Select(DoSomething)

Scala中有类似的东西吗?

例如:

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

3 回答 3

10

在 Scala 中,我们称其为函数;-)。(x,y) => DoSomething(x,y)是匿名函数或闭包,但您可以传递与您正在调用的方法/函数的签名匹配的任何函数,在这种情况下为map. 因此,例如在 scala 中,您可以简单地编写

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

或者

case class Foo(x: Int)
List(1,2,3,4).map(Foo) // here Foo.apply(_) will be called
于 2012-07-20T18:47:17.843 回答
1

经过一些实验,我得出结论,它在 Scala 中的工作方式与在 C# 中的工作方式相同(但不确定它是否实际上是相同的......)

这就是我想要实现的(玩玩 Play!所以 Scala 对我来说是新的,不知道为什么这在我看来不起作用,但是当我在解释器中尝试它时它工作正常)

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
于 2012-07-20T19:49:30.170 回答
0

您实际上可以使用偏函数模拟方法组的行为。但是,这可能不是推荐的方法,因为您强制在运行时发生任何类型错误,并且会产生一些成本来确定调用哪个重载。但是,此代码是否符合您的要求?

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)
}
于 2012-07-20T19:25:53.560 回答