[英]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: 在C#中有一个非常方便的东西叫做方法组,基本上不是写:
someset.Select((x,y) => DoSomething(x,y))
you can write: 你可以写:
someset.Select(DoSomething)
is there something similar in Scala? 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 ;-). 在scala中我们称之为函数;-)。
(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
. (x,y) => DoSomething(x,y)
是一个匿名函数或闭包,但您可以传递任何与您调用的方法/函数的签名相匹配的函数,在本例中为map
。 So for example in scala you can simply write 因此,例如在scala中,您可以简单地编写
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...) 经过一些实验,我得出的结论是它在Scala中的工作方式与在C#中的工作方式相同(不确定它是否实际上是相同的......)
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) 这就是我想要实现的目标(玩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
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.