【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

相关文章
相关标签/搜索