在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));
}
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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)
}