【问题标题】:why unexpected token: * in when doing operation over two lines为什么意外令牌:* 在两行上进行操作时
【发布时间】:2013-08-09 02:53:21
【问题描述】:

在 1.8 控制台中运行以下命令:

def accessories = null
final int prime = 31;
int result = 1;
result = prime
    * result
        + ((accessories == null) ? 0 : accessories
                .hashCode());

我收到一个编译错误说明:

意外标记:* 在第 5 行,第 13 列

然而,当我将“* result”移到上一行时,它会编译并干净地运行。我一直在寻找解释,但到目前为止还没有运气。谁能解释一下?

def accessories = null
final int prime = 31;
int result = 1;
result = prime * result
        + ((accessories == null) ? 0 : accessories
                .hashCode());

【问题讨论】:

    标签: groovy


    【解决方案1】:

    因为 Groovy 的语句不是由; 分隔,而是由换行符分隔。它不能知道下面的行是上面行语句的延续。您可以转义换行符:

    int i = 10 \
        * 9
    assert i == 90
    

    更新:

    实际上,Groovy 确实从上述行中识别出一些语句。至少点被识别:

    assert [1, 2]
      .join("")
      .padLeft(4, "a") == "aa12"
    

    以及带有+-~(可能还有更多)could be methods 的声明:

    def m = "aa"
      - m // fails with "No signature of method: java.lang.String.negative()"
    

    【讨论】:

    • 你只是一针见血。 :-)
    【解决方案2】:

    这是必要的,否则 Groovy 的解析器将不得不做更多的工作。

    有很多地方,即:

    String s = "tim"
                 + "_yates"
    

    解析器可以在哪里计算出你的意思,但在所有这些中,我相信它会涉及到backtracking(或实现两遍解析),这很慢

    【讨论】:

    • +1,不知道解析器中的回溯...我也不太了解解析器:-)
    【解决方案3】:

    您只需将* 移动而不是将* result 移动到第4 行。

    result = prime //Line completes with the assignment of prime to result
            * result //Will yield a compilation error
                + ((accessories == null) ? 0 : accessories
                        .hashCode());
    

    相反,

    result = prime * //Statement expects a RHV (right hand value) for the operator
              result + //Always end the line with an operator
                ((accessories == null) ? 0 : accessories
                        .hashCode());
    

    要使用ternary 运算符进行相同的测试,

    //Yields to compilation error
    def str = "ABC"             
    def val = str == "ABC"
    ? str
    : "XYZ"
    
    //Works perfect
    def val = str == "ABC" ? 
    str : 
    "XYZ"
    

    【讨论】:

    • 这不是我的问题。我的问题是“为什么这是必要的”而不是如何解决它。我已经推断出来了。无论如何,感谢您的反馈。
    • @BillTurner “为什么有必要”在相关行中被称为 cmets。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 2017-02-11
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多