这里是一个简化的解释和美化。
简体,
scala> def f: String => String = {
| val i = 7
| { (x: String) =>
| "y"
| }
| }
<console>:9: error: Int(7) does not take parameters
{ (x: String) =>
^
<console>:12: error: type mismatch;
found : Unit
required: String => String
}
^
因为7
之后的换行符未作为一个分号,对于原因,它可能是一个功能应用此失败;你可能需要一个支撑位于下一行的DSL。 Here is the little nl
in the syntax of an arg with braces.
换行处理的规范的1.2中描述;在本节的最后部分提到了几个像这样的点,其中接受一个nl
。
(两个新行不行,这就是为什么还修复你的问题。)
注意到一个nl
不是在括号前面所接受,所以下面的工作(虽然只的括号,你只得到一个表达你的函数文本):
scala> def g: String => String = {
| val i = 7
| ((x: String) =>
| "y"
|)
| }
g: String => String
其实,对这个问题的代码最好的编辑是不是更括号但数量较少:
scala> def f: String => String = {
| val i = 7
| x: String =>
| "y"
| }
f: String => String
The reason for this nice syntax是你的方法体已经是一个块表达式,并且当一个块的结果表达式是一个函数文本时,你可以简化。
类型的x
也是多余的。
scala> def f: String => String = {
| val i = 7
| x =>
| val a = "a"
| val b = "b"
| a + i + x + b
| }
f: String => String
毫不奇怪:
scala> def f: (String, Int) => String = {
| val i = 7
| (x, j) =>
| x + (i + j)
| }
f: (String, Int) => String
scala> f("bob",70)
res0: String = bob77
什么是编译错误?只是出于好奇:方法是否带有第二个或隐含的参数? –
您是否尝试过使用本地{...}来分隔'val'行和该块? – Beryllium
编译错误是'scales.xml.XPath [列表[scales.utils.Path [scales.xml.XmlItem,scales.xml.Elem,[T] scales.utils.ImmutableArrayProxy [T]]]]不带参数',并且不,它不需要任何第二个或隐含的参数。有一些重名的方法具有相同的名称,但它们都不是。 –