When to use parenthesis in Scala infix notation

前端 未结 4 2014
名媛妹妹
名媛妹妹 2020-11-28 13:09

When programming in Scala, I do more and more functional stuff. However, when using infix notation it is hard to tell when you need parenthesis and when you don\'t.

4条回答
  •  暖寄归人
    2020-11-28 13:25

    This is what I put together for myself after reading the spec:

    • Any method which takes a single parameter can be used as an infix operator: a.m(b) can be written a m b.
    • Any method which does not require a parameter can be used as a postfix operator: a.m can be written a m.

    For instance a.##(b) can be written a ## b and a.! can be written a!

    • Postfix operators have lower precedence than infix operators, so foo bar baz means foo.bar(baz) while foo bar baz bam means (foo.bar(baz)).bam and foo bar baz bam bim means (foo.bar(baz)).bam(bim).
    • Also given a parameterless method m of object a, a.m.m is valid but a m m is not as it would parse as exp1 op exp2.

    Because there is a version of mkString that takes a single parameter it will be seen as an infix opertor in fromFile(file) mkString map caesar(k)_. There is also a version of mkString that takes no parameter which can be used a as postfix operator:

    scala> List(1,2) mkString
    res1: String = 12
    
    scala> List(1,2) mkString "a"
    res2: String = 1a2
    

    Sometime by adding dot in the right location, you can get the precedence you need, e.g. fromFile(file).mkString map { }

    And all that precedence thing happens before typing and other phases, so even though list mkString map function makes no sense as list.mkString(map).function, this is how it will be parsed.

提交回复
热议问题