代码之家  ›  专栏  ›  技术社区  ›  ron

带有curried函数的Scala无点调用语法

  •  1
  • ron  · 技术社区  · 14 年前

    What are the precise rules for when you can omit parenthesis, dots, braces, = (functions), etc.? .

    以下工作:

    scala> List(1,2,3) filter (_ > 1) reduceLeft(_ + _)
    res65: Int = 5
    

    以及以下内容:

    scala> List(1,2,3).filter(_ > 1).foldLeft(0)(_ + _)
    res67: Int = 5
    

    scala> List(1,2,3) filter (_ > 1) foldLeft(0)(_ + _)
    <console>:10: error: 0 of type Int(0) does not take parameters
           List(1,2,3) filter (_ > 1) foldLeft(0)(_ + _)
                                            ^
    

    建议的解决方案是什么?

    2 回复  |  直到 7 年前
        1
  •  7
  •   Community PPrice    7 年前

    这个主题在堆栈溢出问题中有很好的描述 What are the precise rules for when you can omit parenthesis, dots, braces, = (functions), etc.? .

    Curried 函数似乎比只有一个参数的方法难一点。若要省略点,curried函数需要在中缀调用外部使用括号。

    Marimuthu Madasamy mentioned ,它可以工作(对象(列表)、方法(foldLeft)及其第一个参数(0)在括号中):

    (List(1,2,3) filter (_ > 1) foldLeft 0) (_ + _)
    
        2
  •  4
  •   Marimuthu Madasamy    14 年前

    这是有效的:

    (List(1,2,3) filter (_ > 1) foldLeft 0) (_ + _)