我来自What is the formal difference in Scala between braces and parentheses, and when should they be used? ,所以我仍然不清楚scala方法调用语法技巧。我认为该链接中的lcn答案很明确,但这些意思是什么:
val r = List(1, 2, 3).foldLeft(0) _+_ //r: String => String = $Lambda$1642/1200068083@562c1af9
val l = r{"hello"} //l: String = $Lambda$1643/1458648440@23ae6386hello
为什么r
是一个函数?并调用它返回另一个函数l
,并且无法调用l
?
是否在()和{}?
答案 0 :(得分:4)
这与运营商优先级有关:
git reset --hard origin/master
相当于:
val r = List(1, 2, 3).foldLeft(0) _+_
这意味着 - 我们采用部分应用的 val r = (List(1, 2, 3).foldLeft(0) _) + _
函数foldLeft
,其类型为List(1, 2, 3).foldLeft(0) _
,我们调用((Int, Int) => Int) => Int)
它。
现在 - Scala编译器试图找出+ _
运算符对函数应该意味着什么,并且因为+
没有定义这样的运算符,所以它尽力找到合适的运算符< em>隐式转换,并发现Function
确实可以使用Function
方法将String
转换为toString
,以便+ _
表示&#34 ;一个新的匿名函数,它附加传递给List(1, 2, 3).foldLeft(0) _
函数&#34;的字符串表示形式的任何输入字符串。
因此,我们最终得到了String => String
函数,该函数将输入附加到函数toString
的{{1}}结果,即List(1, 2, 3).foldLeft(0) _
:
"<function1>"