有史以来最简单的答案:
从没有参数的方法中删除点是DEPRECATED!
List(1,2,3) reverse //is bad style and will lead to unpredicted behaviour
List(1,2,3) map(_*2) reverse //bad too, because reverse can take first method call from the next line (details below)
可以在采用higher order function 一个参数的方法中删除点,例如map、filter、count 和安全!
另外,purely functional 方法如 zip。
List(1,2,3) map(_*2) filter(_>2)
(List(1,2,3) map(_*2)).reverse //safe and good
List(1,3,5) zip List(2,4,6)
详细回答为什么
case class MyBool(x: Boolean) {
def !!! = MyBool(!x) //postfix
def or(other: MyBool): MyBool = if(x) other else this //infix
def justMethod0() = this //method with empty parameters
def justMethod2(a: MyBool, b: MyBool) = this //method with two or more
override def toString = if(x) "true" else "false"
}
1) 后缀运算符 - 实际上是一个不带参数 (a!==a.!) 且不带括号的方法调用。 (被认为不安全且已弃用)
val b1 = MyBool(false) !!!
List(1,2,3) head
2) 后缀运算符是方法,应该结束行,否则将被视为中缀。
val b1 = MyBool(true) no! no! //ERROR
//is actually parsed like
val b2 = MyBool(true).no!(no!) //(no!) is unknown identifier
//as bad as
Vector(1,2,3) toList map(_*2) //ERROR
3) 中缀操作符是一个参数的方法,可以在没有点和括号的情况下调用。仅适用于purely functional 方法
val c1 = MyBool(true) or b1 or MyBool(true)
val c2 = MyBool(true).or(b1).or(MyBool(true))
c1 == c2
4) 带有一个或多个参数的方法,如果你用参数调用它,它将不带点链接。 def a(), def a(x), def a(x,y)
但是您应该只对使用higher order function 作为参数的方法执行此操作!
val d1 = MyBool(true) justMethod2(b1, c1) or b1 justMethod0() justMethod2(c1, b1)
//yes, it works, but it may be confusing idea
val d2 = MyBool(true).justMethod2(b1,c1).or(b1).justMethod0().justMethod2(c1, b1)
d1 == d2
//looks familiar? This is where it should be used:
List(1,2,3) filter(_>1) map(_*2)
警告示例:
警告:有 1 个弃用警告;使用 -deprecation 重新运行
有关详细信息警告:后缀运算符尾部应通过使
隐含值 scala.language.postfixOps 可见。这可以是
通过添加导入子句'import
scala.language.postfixOps' 或通过设置编译器选项
-语言:后缀操作。请参阅 Scala 文档以获取值 scala.language.postfixOps 以讨论为什么该功能应该是
明确启用。