簡體   English   中英

Scala中C#方法組的等價物是什么?

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

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

在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

經過一些實驗,我得出的結論是它在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

您實際上可以使用部分函數模擬方法組的行為。 但是,它可能不是推薦的方法,因為您強制在運行時發生任何類型錯誤,並且需要花費一些成本來確定要調用的過載。 但是,這段代碼能做你想要的嗎?

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM