【问题标题】:Do I need a trailing semicolon to disambiguate this code?我需要一个尾随分号来消除此代码的歧义吗?
【发布时间】:2019-03-26 00:17:26
【问题描述】:

如果我省略分号,此代码将无法编译。

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

我的猜测是,没有分号,scalac 认为偏函数是\\* 方法的另一个参数,而不是返回值。 (它实际上不是一个偏函数,顺便说一下,它是一个全函数。)

这里可以不用分号吗?在 Scala 中,我从来没有在行尾使用分号。

【问题讨论】:

  • 什么是编译错误?只是出于好奇:\\* 方法是否采用任何第二个或隐式参数?
  • 您是否尝试过使用locally { ... } 来分隔val 行和块?
  • 编译错误是scales.xml.XPath[List[scales.utils.Path[scales.xml.XmlItem,scales.xml.Elem,[T]scales.utils.ImmutableArrayProxy[T]]]] does not take parameters,不,它不需要任何第二个或隐式参数。有一些重载方法具有相同的名称,但它们也没有。
  • @Beryllium 也无法编译。
  • @Robin Green 您是否尝试将块的结果分配给 val 并返回那个?

标签: scala


【解决方案1】:

我会这样写:

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

【讨论】:

  • 这可以更简单,看我的回答。您可以将牙套送回零件箱,帮助保持 la Suisse 甜美。
【解决方案2】:

只需添加第二个换行符,显然相当于分号。

不过,我对此并不完全满意,因为它看起来很脆弱。

【讨论】:

    【解决方案3】:

    这里是简化、解释和美化。

    简化,

    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
    

    【讨论】:

      猜你喜欢
      • 2011-01-03
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多