Scala prefix and infix and postfix operators
Scala中操作符分为
前置操作符(+、-、!、~,这些操作符也是函数)
中置操作符(所有只有一个参数的函数都可以作为中置操作符,比如 "abc" indexOf "a",相当于调用"abc".indexOf("a"))
后置操作符(不带任何参数的函数,比如 123 toString)
前置操作符
scala> ~2 res15: Int = -3 scala> !true res16: Boolean = false scala> -1 res17: Int = -1
中置操作符
scala> 1 to 10 res9: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> 1 -> 10 res10: (Int, Int) = (1,10)
后置操作符
scala> 2.unary_- res18: Int = -2 scala> 1 toString <console>:11: warning: postfix operator toString should be enabled by making the implicit value scala.language.postfixOps visible. This can be achieved by adding the import clause 'import scala.language.postfixOps' or by setting the compiler option -language:postfixOps. See the Scala docs for value scala.language.postfixOps for a discussion why the feature should be explicitly enabled. 1 toString ^ res19: String = 1
看下面这个例子
➜ ~ scala -feature Welcome to Scala 2.12.0-M2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_51). Type in expressions for evaluation. Or try :help. scala> 123 toString <console>:11: warning: postfix operator toString should be enabled by making the implicit value scala.language.postfixOps visible. This can be achieved by adding the import clause 'import scala.language.postfixOps' or by setting the compiler option -language:postfixOps. See the Scala docs for value scala.language.postfixOps for a discussion why the feature should be explicitly enabled. 123 toString ^ res0: String = 123 scala>
scala -feature打开一个console。在这里 toString 是一个后置操作符。这里给出了warning,解决这个问题有两种方式
import scala.language.postfixOps
setting the compiler option -language:postfixOps
还有类似下面这种写法
scala> (1 to 10) toList <console>:11: warning: postfix operator toList should be enabled by making the implicit value scala.language.postfixOps visible. This can be achieved by adding the import clause 'import scala.language.postfixOps' or by setting the compiler option -language:postfixOps. See the Scala docs for value scala.language.postfixOps for a discussion why the feature should be explicitly enabled. (1 to 10) toList ^ res1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
数类型还提供了一元前缀+和-操作符(方法unary_+和unary_-),允许你指示文本数是正的还是负的,如-3或+4.0。如果你没有指定一元的+或-,文本数被解释为正的。一元符号+也存在只是为了与一元符号-相协调,不过没有任何效果。一元符号-还可以用来使变量变成负值。
一元操作符只有一个参数。如果出现在参数之后,就是后置(postfix)操作符;出现在参数之前,就是前置(prefix)了。
如下所示,
scala> 2.unary_- res4: Int = -2 scala> 2.unary_+ res5: Int = 2 scala> -2 res6: Int = -2 scala> +2 res7: Int = 2 scala> 2.unary_~ res8: Int = -3
==========END==========