2013-07-25 30 views
3

如果我省略分号,则此代码不会编译。我是否需要一个尾随分号来消除此代码的歧义?

def checkRadioButton(xml: DslBuilder): String => XmlTree = { 
    val inputs = top(xml).\\*(hasLocalNameX("input")); 
    { (buttonValue: String) => 
     // code omitted 
    } 
} 

我的猜测是,如果没有分号,scalac认为,部分功能是另一种说法为\\*方法,而不是返回值。 (它实际上不是一个局部的功能,顺便说一句,这是一个总的功能。)

我可以不用这里的分号?在Scala之前,我从来没有必要在行尾使用分号。

+2

什么是编译错误?只是出于好奇:方法是否带有第二个或隐含的参数? –

+1

您是否尝试过使用本地{...}来分隔'val'行和该块? – Beryllium

+0

编译错误是'scales.xml.XPath [列表[scales.utils.Path [scales.xml.XmlItem,scales.xml.Elem,[T] scales.utils.ImmutableArrayProxy [T]]]]不带参数',并且不,它不需要任何第二个或隐含的参数。有一些重名的方法具有相同的名称,但它们都不是。 –

回答

2

我会写这样的而不是:

def checkRadioButton(xml: DslBuilder): String => XmlTree = { 
    val inputs = top(xml).\\*(hasLocalNameX("input")); 
    (buttonValue: String) => { // <-- changed position of { 
     // code omitted 
    } 
} 
+0

这可以更简单,请参阅我的答案。你可以把大括号发回零件箱,并帮助保持瑞士甜。 –

2

只需添加一个第二换行,这显然是等价的分号。

不过,我不是这个完全满意,因为它似乎脆弱。

2

这里是一个简化的解释和美化。

简体,

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