前面接触了scala符号,这会整体性的说说。
scala符号主要分为四类:
1. 关键字,保留字 (Keywords/reserved symbols)
2. 自动导入 (Automatically imported methods)
3. 常用方法 (Common methods)
4. 语法糖(Syntactic sugars)
前两章主要讲到了
1.关键字
2.常用方法
这章补充 自动导入,和语法糖
自动导入
任何scala代码中都自动导入了如下:
1
2
3
4
|
//顺序无关
import
java.lang.
_
import
scala.
_
import
scala.Predef.
_
|
主要看第三行 Predef
他包含了所有的隐士转换和方法导入
见 http://www.scala-lang.org/api/current/index.html#scala.Predef$
如:<:<
1
2
|
sealed abstract class <:<[-From, +To] extends (From) To with Serializable
An instance of A <:< B witnesses that A is a subtype of B.
|
又如: =:=
1
2
|
sealed abstract class =:=[From, To] extends (From) To with Serializable
An instance of A =:= B witnesses that the types A and B are equal.
|
我们能够看到更多的导入符号在index 复制如下:
http://www.scala-lang.org/files/archive/nightly/docs/library/index.html#index.index-_
语法糖
对于老程序员Syntactic sugars是个很有意思的东西,但是对于新人来说,第一概念陌生,第二不会用,反而更加容易晕头转向。
我们先了解下传统意义上对Syntactic sugars理解: 隐藏更多细节让代码便于使用
那我们看看scala 如何官方用代码做一次语法糖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class
Example(arr
:
Array[Int]
=
Array.fill(
5
)(
0
)) {
def
apply(n
:
Int)
=
arr(n)
def
update(n
:
Int, v
:
Int)
=
arr(n)
=
v
def
a
=
arr(
0
);
def
a
_=
(v
:
Int)
=
arr(
0
)
=
v
def
b
=
arr(
1
);
def
b
_=
(v
:
Int)
=
arr(
1
)
=
v
def
c
=
arr(
2
);
def
c
_=
(v
:
Int)
=
arr(
2
)
=
v
def
d
=
arr(
3
);
def
d
_=
(v
:
Int)
=
arr(
3
)
=
v
def
e
=
arr(
4
);
def
e
_=
(v
:
Int)
=
arr(
4
)
=
v
def
+(v
:
Int)
=
new
Example(arr map (
_
+ v))
def
unapply(n
:
Int)
=
if
(arr.indices contains n) Some(arr(n))
else
None
}
var
ex
=
new
Example
println(ex(
0
))
// calls apply(0)
ex(
0
)
=
2
// 更新数组的第一个值为2 原官方解释有误
ex.b
=
3
// calls b_=(3)
val
ex(c)
=
2
// calls unapply(2) and assigns result to c
ex +
=
1
// substituted for ex = ex + 1
|
先适应下scala的语法 如:
1
|
def
a
_=
(v
:
Int)
=
arr(
0
)
=
v
|
实际上 a_= 是方法名, 第二个= 号 是指后面即将跟上方法体, arr(0) = v是方法
1
2
3
|
def
a
_=
(v
:
Int)
=
{
arr(
0
)
=
v
}
|
我们可以把ex简单的得到一些值理解为对一种Syntactic sugars
让我们看看官方给出的2个常见例子:
1
2
|
++
=
||
=
|
而实际上++= index 中已经给出,并且在多个继承类中重写其实现。
而 ||=至今我也没有找到其出处,还不够熟悉。有一些针对symbol的讨论,见地址:
http://stackoverflow.com/questions/7888944/scala-punctuation-aka-symbols-and-operators
对scala的符号讨论算是结束了,相信下一次各位再碰到scala让人抓狂的语法时,会有一个入手点。
补充一个,这两个符号如何应用
1
2
|
<
:
<
:
<
|
见http://www.scala-lang.org/api/current/index.html#scala.Tuple2 invert的方法。
over