Scala - infix vs dot notation

前端 未结 4 850
忘了有多久
忘了有多久 2020-12-07 23:00

Is there a best practice for one over the other? I\'ve been reading the Scala book by Odersky, et al. and it seems like infix is used for a lot of the Collections

4条回答
  •  时光取名叫无心
    2020-12-07 23:15

    There is a good style guide in official Scala site documentation that describe proper usage infix notation over dot notation.

    Suffix Notation:

    names.toList
    // is the same as
    names toList // Unsafe, don't use!
    

    Arity-1:

    // right!
    names foreach (n => println(n))
    names mkString ","
    optStr getOrElse ""
    // wrong!
    javaList add item
    

    Higher-Order Functions:

    // wrong!
    names.map (_.toUpperCase).filter (_.length > 5)
    // right!
    names map (_.toUpperCase) filter (_.length > 5)
    

    Symbolic methods/Operators:

    // right!
    "daniel" + " " + "Spiewak"
    // wrong!
    "daniel"+" "+"spiewak"
    

提交回复
热议问题