Scala prefix and infix and postfix operatorses6
Scala中操做符分爲shell
前置操做符(+、-、!、~,這些操做符也是函數)express
中置操做符(全部只有一個參數的函數均可以做爲中置操做符,好比 "abc" indexOf "a",至關於調用"abc".indexOf("a"))函數
後置操做符(不帶任何參數的函數,好比 123 toString)post
前置操做符lua
scala> ~2 res15: Int = -3 scala> !true res16: Boolean = false scala> -1 res17: Int = -1
中置操做符es5
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)
後置操做符spa
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
➜ ~ 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,解決這個問題有兩種方式code
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==========