男孩,這是一個微妙的,但據我所知它完全遵循Scala spec。我將從規範2.9版引用。
對於您的第一個例子:
The expression e _ is well-formed if e is of method type or if e is a call-by-name parameter. If e is a method with parameters, e _ represents e converted to a function type by eta expansion.
爲ETA擴張的算法§給出:當你正確地說,你是通過方法值(§6.7)的一個特例看到埃塔膨脹6.26.5它可以跟隨,得到下列替換爲表達式new Foo().x1 _
:
{
val x1 = new Foo();
(y1: Int) => x1.(y1);
}
這意味着,當正在使用ETA膨脹,所有的子表達式在點所在的C評價發生反轉(如果我已經正確理解短語「最大子表達式」的含義)並且最終表達式是創建匿名函數。
在第二個例子中,這些額外的括號意味着,編譯器會看§6.23(具體而言,「佔位符語法匿名函數)和直接創建一個匿名函數。
An expression (of syntactic category Expr) may contain embedded underscore symbols _ at places where identifiers are legal. Such an expression represents an anonymous function where subsequent occurrences of underscores denote successive parameters.
在這種情況下, ,並在該部分中的算法如下,表達式結束是這樣的:
(x1: Int) => new Foo().foo(x1)
的差別是細微的和,如通過@Antoras很好的解釋,實際上只顯示了在存在的副作用代碼。
請注意,針對涉及按名稱代碼塊的情況正在進行錯誤修復(請參閱,例如,this question,this bug和this bug)。
後記:在這兩種情況下,匿名函數(x1:Int) => toto
被擴大到
new scala.Function1[Int, Int] {
def apply(x1: Int): Int = toto
}
來源
2012-05-28 22:14:08
rxg
這個問題有了答案,但我看不到它了。有人刪除它嗎? –