scala方法调用技巧List(1,2,3).foldLeft(0)_ + _

时间:2018-05-15 15:25:39

标签: scala

我来自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
  1. 为什么r是一个函数?并调用它返回另一个函数l,并且无法调用l

  2. 是否在()和{}?

  3. 中有一些方法调用的官方文档

1 个答案:

答案 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>"