Scala prefix and infix and postfix operators

Scala prefix and infix and postfix operatorses6


prefix and infix and postfix operators

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 operator

数类型还提供了一元前缀+和-操做符(方法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==========

相关文章
相关标签/搜索