When to use parenthesis in Scala infix notation

前端 未结 4 2012
名媛妹妹
名媛妹妹 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:32

    Here's a simple rule: never used postfix operators. If you do, put the whole expression ending with the postfix operator inside parenthesis.

    In fact, starting with Scala 2.10.0, doing that will generate a warning by default.

    For good measure, you might want to move the postfix operator out, and use dot notation for it. For example:

    (fromFile(file)).mkString map caesar(k)_
    

    Or, even more simply,

    fromFile(file).mkString map caesar(k)_
    

    On the other hand, pay attention to the methods where you can supply an empty parenthesis to turn them into infix:

    fromFile(file) mkString () map caesar(k)_
    

提交回复
热议问题