【scala初學】scala symbol 符號 -3

   前面接觸了scala符號,這會總體性的說說。html

scala符號主要分爲四類:
 1. 關鍵字,保留字 (Keywords/reserved symbols)java

 2. 自動導入 (Automatically imported methods)程序員

 3. 經常使用方法 (Common methods)api

 4. 語法糖(Syntactic sugars)數組


 前兩章主要講到了
1.關鍵字app

2.經常使用方法
 ide

這章補充 自動導入,和語法糖spa

 

自動導入scala

任何scala代碼中都自動導入了以下:htm

//順序無關
import java.lang._
import scala._
import scala.Predef._

主要看第三行  Predef

他包含了全部的隱士轉換和方法導入

http://www.scala-lang.org/api/current/index.html#scala.Predef$

如:<:<

sealed abstract  class  <:<[-From, +To] extends (From)  To with Serializable
An instance of A <:< B witnesses that A is a subtype of B.

 又如: =:=

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 如何官方用代碼作一次語法糖

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的語法 如:

 def a_=(v: Int) = arr(0) = v

實際上 a_= 是方法名, 第二個= 號 是指後面即將跟上方法體, arr(0) = v是方法

def a_= (v: Int) = {    
 arr(0) = v 
}

咱們能夠把ex簡單的獲得一些值理解爲對一種Syntactic sugars

讓咱們看看官方給出的2個常見例子:

++=
||=

而實際上++= index 中已經給出,而且在多個繼承類中重寫其實現。

而 ||=至今我也沒有找到其出處,還不夠熟悉。有一些針對symbol的討論,見地址:

http://stackoverflow.com/questions/7888944/scala-punctuation-aka-symbols-and-operators

 

對scala的符號討論算是結束了,相信下一次各位再碰到scala讓人抓狂的語法時,會有一個入手點。

 

補充一個,這兩個符號如何應用

<:
<:<

http://www.scala-lang.org/api/current/index.html#scala.Tuple2  invert的方法。

 

 

 

over

相關文章
相關標籤/搜索