Scala語法總結

1.包

   a.    package com.runoob

          class HelloWorld

   b.     package com.runoob {

               class HelloWorld

            }

2.import

import java.awt.{Color, Font}

// 重命名成員

import java.util.{HashMap => JavaHashMap}

// 隱藏成員

import java.util.{HashMap => _, _} // 引入了util包的所有成員,但是HashMap被隱藏了

3.多行字符串

val foo = """菜鳥教程

www.runoob.com

www.w3cschool.cc

www.runnoob.com

以上三個地址都能訪問"""

4.變量

使用關鍵詞 "var" 聲明變量,使用關鍵詞 "val" 聲明常量。

var myVar : String = "Foo"

val myVal : String = "Too"

如果程序嘗試修改常量 myVal 的值,程序將會在編譯時報錯。

var myVar = 10;

val myVal = "Hello, Scala!";

val xmax, ymax = 100  // xmax, ymax都聲明爲100

5.private[x]

這裏的x指代某個所屬的包、類或單例對象。如果寫成private[x],讀作"這個成員除了對[…]中的類或[…]中的包中的類及它們的伴生對像可見外,對其它所有類都是private。

6.方法

a.       def functionName ([參數列表]) : [return type] = {

                function body

                return [expr]

           }

b.  如果你不寫等於號和方法主體,那麼方法會被隱式聲明爲抽象(abstract),包含它的類型於是也是一個抽象類型。

如果方法沒有返回值,可以返回爲 Unit,這個類似於 Java 的 void

            c.  String方法

                 下表列出了 java.lang.String 中常用的方法,你可以在 Scala 中使用:

序號

方法及描述

1

char charAt(int index)

返回指定位置的字符

2

int compareTo(Object o)

比較字符串與對象

3

int compareTo(String anotherString)

按字典順序比較兩個字符串

4

int compareToIgnoreCase(String str)

按字典順序比較兩個字符串,不考慮大小寫

5

String concat(String str)

將指定字符串連接到此字符串的結尾

6

boolean contentEquals(StringBuffer sb)

將此字符串與指定的 StringBuffer 比較。

7

static String copyValueOf(char[] data)

返回指定數組中表示該字符序列的 String

8

static String copyValueOf(char[] data, int offset, int count)

返回指定數組中表示該字符序列的 String

9

boolean endsWith(String suffix)

測試此字符串是否以指定的後綴結束

10

boolean equals(Object anObject)

將此字符串與指定的對象比較

11

boolean equalsIgnoreCase(String anotherString)

將此 String 與另一個 String 比較,不考慮大小寫

12

byte getBytes()

使用平臺的默認字符集將此 String 編碼爲 byte 序列,並將結果存儲到一個新的 byte 數組中

13

byte[] getBytes(String charsetName

使用指定的字符集將此 String 編碼爲 byte 序列,並將結果存儲到一個新的 byte 數組中

14

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

將字符從此字符串複製到目標字符數組

15

int hashCode()

返回此字符串的哈希碼

16

int indexOf(int ch)

返回指定字符在此字符串中第一次出現處的索引

17

int indexOf(int ch, int fromIndex)

返回在此字符串中第一次出現指定字符處的索引,從指定的索引開始搜索

18

int indexOf(String str)

返回指定子字符串在此字符串中第一次出現處的索引

19

int indexOf(String str, int fromIndex)

返回指定子字符串在此字符串中第一次出現處的索引,從指定的索引開始

20

String intern()

返回字符串對象的規範化表示形式

21

int lastIndexOf(int ch)

返回指定字符在此字符串中最後一次出現處的索引

22

int lastIndexOf(int ch, int fromIndex)

返回指定字符在此字符串中最後一次出現處的索引,從指定的索引處開始進行反向搜索

23

int lastIndexOf(String str)

返回指定子字符串在此字符串中最右邊出現處的索引

24

int lastIndexOf(String str, int fromIndex)

返回指定子字符串在此字符串中最後一次出現處的索引,從指定的索引開始反向搜索

25

int length()

返回此字符串的長度

26

boolean matches(String regex)

告知此字符串是否匹配給定的正則表達式

27

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)

測試兩個字符串區域是否相等

28

boolean regionMatches(int toffset, String other, int ooffset, int len)

測試兩個字符串區域是否相等

29

String replace(char oldChar, char newChar)

返回一個新的字符串,它是通過用 newChar 替換此字符串中出現的所有 oldChar 得到的

30

String replaceAll(String regex, String replacement

使用給定的 replacement 替換此字符串所有匹配給定的正則表達式的子字符串

31

String replaceFirst(String regex, String replacement)

使用給定的 replacement 替換此字符串匹配給定的正則表達式的第一個子字符串

32

String[] split(String regex)

根據給定正則表達式的匹配拆分此字符串

33

String[] split(String regex, int limit)

根據匹配給定的正則表達式來拆分此字符串

34

boolean startsWith(String prefix)

測試此字符串是否以指定的前綴開始

35

boolean startsWith(String prefix, int toffset)

測試此字符串從指定索引開始的子字符串是否以指定前綴開始。

36

CharSequence subSequence(int beginIndex, int endIndex)

返回一個新的字符序列,它是此序列的一個子序列

37

String substring(int beginIndex)

返回一個新的字符串,它是此字符串的一個子字符串

38

String substring(int beginIndex, int endIndex)

返回一個新字符串,它是此字符串的一個子字符串

39

char[] toCharArray()

將此字符串轉換爲一個新的字符數組

40

String toLowerCase()

使用默認語言環境的規則將此 String 中的所有字符都轉換爲小寫

41

String toLowerCase(Locale locale)

使用給定 Locale 的規則將此 String 中的所有字符都轉換爲小寫

42

String toString()

返回此對象本身(它已經是一個字符串!)

43

String toUpperCase()

使用默認語言環境的規則將此 String 中的所有字符都轉換爲大寫

44

String toUpperCase(Locale locale)

使用給定 Locale 的規則將此 String 中的所有字符都轉換爲大寫

45

String trim()

刪除指定字符串的首尾空白符

46

static String valueOf(primitive data type x)

返回指定類型參數的字符串表示形式

7.數組

數組

             var z:Array[String] = new Array[String](3)

             或

             var z = new Array[String](3)

             z(0) = "Runoob"; z(1) = "Baidu"; z(4/2) = "Google"

             var z = Array("Runoob", "Baidu", "Google")

多維數組

              var myMatrix = ofDim[Int](3,3)

數組方法

                        下表中爲 Scala 語言中處理數組的重要方法,使用它前我們需要使用 import Array._ 引入包。

序號

方法和描述

1

def apply( x: T, xs: T* ): Array[T]

創建指定對象 T 的數組, T 的值可以是 Unit, Double, Float, Long, Int, Char, Short, Byte, Boolean。

2

def concat[T]( xss: Array[T]* ): Array[T]

合併數組

3

def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): Unit

複製一個數組到另一個數組上。相等於 Java's System.arraycopy(src, srcPos, dest, destPos, length)。

4

def empty[T]: Array[T]

返回長度爲 0 的數組

5

def iterate[T]( start: T, len: Int )( f: (T) => T ): Array[T]

返回指定長度數組,每個數組元素爲指定函數的返回值。

以上實例數組初始值爲 0,長度爲 3,計算函數爲a=>a+1

scala> Array.iterate(0,3)(a=>a+1)
res1: Array[Int] = Array(0, 1, 2)

6

def fill[T]( n: Int )(elem: => T): Array[T]

返回數組,長度爲第一個參數指定,同時每個元素使用第二個參數進行填充。

7

def fill[T]( n1: Int, n2: Int )( elem: => T ): Array[Array[T]]

返回二數組,長度爲第一個參數指定,同時每個元素使用第二個參數進行填充。

8

def ofDim[T]( n1: Int ): Array[T]

創建指定長度的數組

9

def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]]

創建二維數組

10

def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]]

創建三維數組

11

def range( start: Int, end: Int, step: Int ): Array[Int]

創建指定區間內的數組,step 爲每個元素間的步長

12

def range( start: Int, end: Int ): Array[Int]

創建指定區間內的數組

13

def tabulate[T]( n: Int )(f: (Int)=> T): Array[T]

返回指定長度數組,每個數組元素爲指定函數的返回值,默認從 0 開始。

以上實例返回 3 個元素:

scala> Array.tabulate(3)(a => a + 5)
res0: Array[Int] = Array(5, 6, 7)

14

def tabulate[T]( n1: Int, n2: Int )( f: (Int, Int ) => T): Array[Array[T]]

返回指定長度的二維數組,每個數組元素爲指定函數的返回值,默認從 0 開始。

8.集合

        List

        1.  定義

// 字符串列表
val site: List[String] = List("Runoob", "Google", "Baidu")
				
// 整型列表
val nums: List[Int] = List(1, 2, 3, 4)

// 空列表
val empty: List[Nothing] = List()
				
// 二維列表
val dim: List[List[Int]] =
List(
	 List(1, 0, 0),
	 List(0, 1, 0),
	 List(0, 0, 1)
	)
				
// 字符串列表
val site = "Runoob" :: ("Google" :: ("Baidu" :: Nil))

 

        2.  連接列表

                   使用 ::: 運算符或 List.:::() 方法或 List.concat() 方法來連接兩個或多個列表。

        3.  List.fill()

                    val site = List.fill(3)("Runoob") // 重複 Runoob 3次

         4.  List.tabulate()

                     // 通過給定的函數創建 6 個元素

                     val squares = List.tabulate(6)(n => n * n)

         5.  Scala List 常用方法

              下表列出了 Scala List 常用的方法:

序號

方法及描述

1

def +:(elem: A): List[A]

爲列表預添加元素

scala> val x = List(1)
x: List[Int] = List(1)

scala> val y = 2 +: x
y
: List[Int] = List(2, 1)

scala> println(x)
List(1)

2

def ::(x: A): List[A]

在列表開頭添加元素

3

def :::(prefix: List[A]): List[A]

在列表開頭添加指定列表的元素

4

def :+(elem: A): List[A]

複製添加元素後列表。

scala> val a = List(1)
a: List[Int] = List(1)

scala> val b = a :+ 2
b: List[Int] = List(1, 2)

scala> println(a)
List(1)

5

def addString(b: StringBuilder): StringBuilder

將列表的所有元素添加到 StringBuilder

6

def addString(b: StringBuilder, sep: String): StringBuilder

將列表的所有元素添加到 StringBuilder,並指定分隔符

7

def apply(n: Int): A

通過列表索引獲取元素

8

def contains(elem: Any): Boolean

檢測列表中是否包含指定的元素

9

def copyToArray(xs: Array[A], start: Int, len: Int): Unit

將列表的元素複製到數組中。

10

def distinct: List[A]

去除列表的重複元素,並返回新列表

11

def drop(n: Int): List[A]

丟棄前n個元素,並返回新列表

12

def dropRight(n: Int): List[A]

丟棄最後n個元素,並返回新列表

13

def dropWhile(p: (A) => Boolean): List[A]

從左向右丟棄元素,直到條件p不成立

14

def endsWith[B](that: Seq[B]): Boolean

檢測列表是否以指定序列結尾

15

def equals(that: Any): Boolean

判斷是否相等

16

def exists(p: (A) => Boolean): Boolean

判斷列表中指定條件的元素是否存在。

判斷l是否存在某個元素:

scala> l.exists(s => s == "Hah")
res7: Boolean = true

17

def filter(p: (A) => Boolean): List[A]

輸出符號指定條件的所有元素。

過濾出長度爲3的元素:

scala> l.filter(s => s.length == 3)
res8: List[String] = List(Hah, WOW)

18

def forall(p: (A) => Boolean): Boolean

檢測所有元素。

例如:判斷所有元素是否以"H"開頭:

scala> l.forall(s => s.startsWith("H")) res10: Boolean = false

19

def foreach(f: (A) => Unit): Unit

將函數應用到列表的所有元素

20

def head: A

獲取列表的第一個元素

21

def indexOf(elem: A, from: Int): Int

從指定位置 from 開始查找元素第一次出現的位置

22

def init: List[A]

返回所有元素,除了最後一個

23

def intersect(that: Seq[A]): List[A]

計算多個集合的交集

24

def isEmpty: Boolean

檢測列表是否爲空

25

def iterator: Iterator[A]

創建一個新的迭代器來迭代元素

26

def last: A

返回最後一個元素

27

def lastIndexOf(elem: A, end: Int): Int

在指定的位置 end 開始查找元素最後出現的位置

28

def length: Int

返回列表長度

29

def map[B](f: (A) => B): List[B]

通過給定的方法將所有元素重新計算

30

def max: A

查找最大元素

31

def min: A

查找最小元素

32

def mkString: String

列表所有元素作爲字符串顯示

33

def mkString(sep: String): String

使用分隔符將列表所有元素作爲字符串顯示

34

def reverse: List[A]

列表反轉

35

def sorted[B >: A]: List[A]

列表排序

36

def startsWith[B](that: Seq[B], offset: Int): Boolean

檢測列表在指定位置是否包含指定序列

37

def sum: A

計算集合元素之和

38

def tail: List[A]

返回所有元素,除了第一個

39

def take(n: Int): List[A]

提取列表的前n個元素

40

def takeRight(n: Int): List[A]

提取列表的後n個元素

41

def toArray: Array[A]

列表轉換爲數組

42

def toBuffer[B >: A]: Buffer[B]

返回緩衝區,包含了列表的所有元素

43

def toMap[T, U]: Map[T, U]

List 轉換爲 Map

44

def toSeq: Seq[A]

List 轉換爲 Seq

45

def toSet[B >: A]: Set[B]

List 轉換爲 Set

46

def toString(): String

列表轉換爲字符串

         Set

              Scala Set(集合)是沒有重複的對象集合,所有的元素都是唯一的。

              下表列出了 Scala Set 常用的方法:

序號

方法及描述

1

def +(elem: A): Set[A]

爲集合添加新元素,x並創建一個新的集合,除非元素已存在

2

def -(elem: A): Set[A]

移除集合中的元素,並創建一個新的集合

3

def contains(elem: A): Boolean

如果元素在集合中存在,返回 true,否則返回 false。

4

def &(that: Set[A]): Set[A]

返回兩個集合的交集

5

def &~(that: Set[A]): Set[A]

返回兩個集合的差集

6

def +(elem1: A, elem2: A, elems: A*): Set[A]

通過添加傳入指定集合的元素創建一個新的不可變集合

7

def ++(elems: A): Set[A]

合併兩個集合

8

def -(elem1: A, elem2: A, elems: A*): Set[A]

通過移除傳入指定集合的元素創建一個新的不可變集合

9

def addString(b: StringBuilder): StringBuilder

將不可變集合的所有元素添加到字符串緩衝區

10

def addString(b: StringBuilder, sep: String): StringBuilder

將不可變集合的所有元素添加到字符串緩衝區,並使用指定的分隔符

11

def apply(elem: A)

檢測集合中是否包含指定元素

12

def count(p: (A) => Boolean): Int

計算滿足指定條件的集合元素個數

13

def copyToArray(xs: Array[A], start: Int, len: Int): Unit

複製不可變集合元素到數組

14

def diff(that: Set[A]): Set[A]

比較兩個集合的差集

15

def drop(n: Int): Set[A]]

返回丟棄前n個元素新集合

16

def dropRight(n: Int): Set[A]

返回丟棄最後n個元素新集合

17

def dropWhile(p: (A) => Boolean): Set[A]

從左向右丟棄元素,直到條件p不成立

18

def equals(that: Any): Boolean

equals 方法可用於任意序列。用於比較系列是否相等。

19

def exists(p: (A) => Boolean): Boolean

判斷不可變集合中指定條件的元素是否存在。

20

def filter(p: (A) => Boolean): Set[A]

輸出符合指定條件的所有不可變集合元素。

21

def find(p: (A) => Boolean): Option[A]

查找不可變集合中滿足指定條件的第一個元素

22

def forall(p: (A) => Boolean): Boolean

查找不可變集合中滿足指定條件的所有元素

23

def foreach(f: (A) => Unit): Unit

將函數應用到不可變集合的所有元素

24

def head: A

獲取不可變集合的第一個元素

25

def init: Set[A]

返回所有元素,除了最後一個

26

def intersect(that: Set[A]): Set[A]

計算兩個集合的交集

27

def isEmpty: Boolean

判斷集合是否爲空

28

def iterator: Iterator[A]

創建一個新的迭代器來迭代元素

29

def last: A

返回最後一個元素

30

def map[B](f: (A) => B): immutable.Set[B]

通過給定的方法將所有元素重新計算

31

def max: A

查找最大元素

32

def min: A

查找最小元素

33

def mkString: String

集合所有元素作爲字符串顯示

34

def mkString(sep: String): String

使用分隔符將集合所有元素作爲字符串顯示

35

def product: A

返回不可變集合中數字元素的積。

36

def size: Int

返回不可變集合元素的數量

37

def splitAt(n: Int): (Set[A], Set[A])

把不可變集合拆分爲兩個容器,第一個由前 n 個元素組成,第二個由剩下的元素組成

38

def subsetOf(that: Set[A]): Boolean

如果集合中含有子集返回 true,否則返回false

39

def sum: A

返回不可變集合中所有數字元素之和

40

def tail: Set[A]

返回一個不可變集合中除了第一元素之外的其他元素

41

def take(n: Int): Set[A]

返回前 n 個元素

42

def takeRight(n: Int):Set[A]

返回後 n 個元素

43

def toArray: Array[A]

將集合轉換爲數組

44

def toBuffer[B >: A]: Buffer[B]

返回緩衝區,包含了不可變集合的所有元素

45

def toList: List[A]

返回 List,包含了不可變集合的所有元素

46

def toMap[T, U]: Map[T, U]

返回 Map,包含了不可變集合的所有元素

47

def toSeq: Seq[A]

返回 Seq,包含了不可變集合的所有元素

48

def toString(): String

返回一個字符串,以對象來表示

        Map

序號

方法及描述

1

def ++(xs: Map[(A, B)]): Map[A, B]

返回一個新的 Map,新的 Map xs 組成

2

def -(elem1: A, elem2: A, elems: A*): Map[A, B]

返回一個新的 Map, 移除 key 爲 elem1, elem2 或其他 elems。

3

def --(xs: GTO[A]): Map[A, B]

返回一個新的 Map, 移除 xs 對象中對應的 key

4

def get(key: A): Option[B]

返回指定 key 的值

5

def iterator: Iterator[(A, B)]

創建新的迭代器,並輸出 key/value 對

6

def addString(b: StringBuilder): StringBuilder

將 Map 中的所有元素附加到StringBuilder,可加入分隔符

7

def addString(b: StringBuilder, sep: String): StringBuilder

將 Map 中的所有元素附加到StringBuilder,可加入分隔符

8

def apply(key: A): B

返回指定鍵的值,如果不存在返回 Map 的默認方法

9

def clear(): Unit

清空 Map

10

def clone(): Map[A, B]

從一個 Map 複製到另一個 Map

11

def contains(key: A): Boolean

如果 Map 中存在指定 key,返回 true,否則返回 false。

12

def copyToArray(xs: Array[(A, B)]): Unit

複製集合到數組

13

def count(p: ((A, B)) => Boolean): Int

計算滿足指定條件的集合元素數量

14

def default(key: A): B

定義 Map 的默認值,在 key 不存在時返回。

15

def drop(n: Int): Map[A, B]

返回丟棄前n個元素新集合

16

def dropRight(n: Int): Map[A, B]

返回丟棄最後n個元素新集合

17

def dropWhile(p: ((A, B)) => Boolean): Map[A, B]

從左向右丟棄元素,直到條件p不成立

18

def empty: Map[A, B]

返回相同類型的空 Map

19

def equals(that: Any): Boolean

如果兩個 Map 相等(key/value 均相等),返回true,否則返回false

20

def exists(p: ((A, B)) => Boolean): Boolean

判斷集合中指定條件的元素是否存在

21

def filter(p: ((A, B))=> Boolean): Map[A, B]

返回滿足指定條件的所有集合

22

def filterKeys(p: (A) => Boolean): Map[A, B]

返回符合指定條件的不可變 Map

23

def find(p: ((A, B)) => Boolean): Option[(A, B)]

查找集合中滿足指定條件的第一個元素

24

def foreach(f: ((A, B)) => Unit): Unit

將函數應用到集合的所有元素

25

def init: Map[A, B]

返回所有元素,除了最後一個

26

def isEmpty: Boolean

檢測 Map 是否爲空

27

def keys: Iterable[A]

返回所有的key/p>

28

def last: (A, B)

返回最後一個元素

29

def max: (A, B)

查找最大元素

30

def min: (A, B)

查找最小元素

31

def mkString: String

集合所有元素作爲字符串顯示

32

def product: (A, B)

返回集合中數字元素的積。

33

def remove(key: A): Option[B]

移除指定 key

34

def retain(p: (A, B) => Boolean): Map.this.type

如果符合滿足條件的返回 true

35

def size: Int

返回 Map 元素的個數

36

def sum: (A, B)

返回集合中所有數字元素之和

37

def tail: Map[A, B]

返回一個集合中除了第一元素之外的其他元素

38

def take(n: Int): Map[A, B]

返回前 n 個元素

39

def takeRight(n: Int): Map[A, B]

返回後 n 個元素

40

def takeWhile(p: ((A, B)) => Boolean): Map[A, B]

返回滿足指定條件的元素

41

def toArray: Array[(A, B)]

集合轉數組

42

def toBuffer[B >: A]: Buffer[B]

返回緩衝區,包含了 Map 的所有元素

43

def toList: List[A]

返回 List,包含了 Map 的所有元素

44

def toSeq: Seq[A]

返回 Seq,包含了 Map 的所有元素

45

def toSet: Set[A]

返回 Set,包含了 Map 的所有元素

46

def toString(): String

返回字符串對象

           tuple元組

與列表一樣,元組也是不可變的,但與列表不同的是元組可以包含不同類型的元素。

元組的值是通過將單個的值包含在圓括號中構成的。例如:

val t = (1, 3.14, "Fred") 

以上實例在元組中定義了三個元素,對應的類型分別爲[Int, Double, java.lang.String]。

此外我們也可以使用以上方式來定義:

val t = new Tuple3(1, 3.14, "Fred")

元組的實際類型取決於它的元素的類型,比如 (99, "runoob") 是 Tuple2[Int, String]。 ('u', 'r', "the", 1, 4, "me") 爲 Tuple6[Char, Char, String, Int, Int, String]。

目前 Scala 支持的元組最大長度爲 22。對於更大長度你可以使用集合,或者擴展元組。

訪問元組的元素可以通過數字索引,如下一個元組:

val t = (4,3,2,1)

我們可以使用 t._1 訪問第一個元素, t._2 訪問第二個元素,如下所示:

object Test {
   def main(args: Array[String]) {
      val t = (4,3,2,1)

val sum = t._1 + t._2 + t._3 + t._4

println( "元素之和爲: "  + sum )
   }
}

執行以上代碼,輸出結果爲:

$ scalac Test.scala
$ scala
Test
元素之和爲: 10

 

迭代元組

你可以使用 Tuple.productIterator() 方法來迭代輸出元組的所有元素:

object Test {
   def main(args: Array[String]) {
      val t = (4,3,2,1)
     
      t
.productIterator.foreach{ i =>println("Value = " + i )}
   }
}

執行以上代碼,輸出結果爲:

$ scalac Test.scala
$ scala
Test
Value = 4
Value = 3
Value = 2
Value = 1

 

元組轉爲字符串

你可以使用 Tuple.toString() 方法將元組的所有元素組合成一個字符串,實例如下:

object Test {
   def main(args: Array[String]) {
      val t = new Tuple3(1, "hello", Console)
     
      println
("連接後的字符串爲: " + t.toString() )
   }
}

執行以上代碼,輸出結果爲:

$ scalac Test.scala
$ scala
Test
連接後的字符串爲: (1,hello,scala.Console$@4dd8dc3)

 

元素交換

你可以使用 Tuple.swap 方法來交換元組的元素。如下實例:

object Test {
   def main(args: Array[String]) {
      val t = new Tuple2("www.google.com", "www.runoob.com")
     
      println
("交換後的元組: " + t.swap )
   }
}

執行以上代碼,輸出結果爲:

$ scalac Test.scala
$ scala
Test
交換後的元組: (www.runoob.com,www.google.com)

 

Option(選項)

序號

方法及描述

1

def get: A

獲取可選值

2

def isEmpty: Boolean

檢測可選類型值是否爲 None,是的話返回 true,否則返回 false

3

def productArity: Int

返回元素個數, A(x_1, ..., x_k), 返回 k

4

def productElement(n: Int): Any

獲取指定的可選項,以 0 爲起始。即 A(x_1, ..., x_k), 返回 x_(n+1) , 0 < n < k.

5

def exists(p: (A) => Boolean): Boolean

如果可選項中指定條件的元素存在且不爲 None 返回 true,否則返回 false。

6

def filter(p: (A) => Boolean): Option[A]

如果選項包含有值,而且傳遞給 filter 的條件函數返回 true, filter 會返回 Some 實例。 否則,返回值爲 None 。

7

def filterNot(p: (A) => Boolean): Option[A]

如果選項包含有值,而且傳遞給 filter 的條件函數返回 false, filter 會返回 Some 實例。 否則,返回值爲 None 。

8

def flatMap[B](f: (A) => Option[B]): Option[B]

如果選項包含有值,則傳遞給函數 f 處理後返回,否則返回 None

9

def foreach[U](f: (A) => U): Unit

如果選項包含有值,則將每個值傳遞給函數 f, 否則不處理。

10

def getOrElse[B >: A](default: => B): B

如果選項包含有值,返回選項值,否則返回設定的默認值。

11

def isDefined: Boolean

如果可選值是 Some 的實例返回 true,否則返回 false。

12

def iterator: Iterator[A]

如果選項包含有值,迭代出可選值。如果可選值爲空則返回空迭代器。

13

def map[B](f: (A) => B): Option[B]

如果選項包含有值, 返回由函數 f 處理後的 Some,否則返回 None

14

def orElse[B >: A](alternative: => Option[B]): Option[B]

如果一個 Option 是 None , orElse 方法會返回傳名參數的值,否則,就直接返回這個 Option。

15

def orNull

如果選項包含有值返回選項值,否則返回 null。

 Iterator(迭代器)

序號

方法及描述

1

def hasNext: Boolean

如果還有可返回的元素,返回true。

2

def next(): A

返回迭代器的下一個元素,並且更新迭代器的狀態

3

def ++(that: => Iterator[A]): Iterator[A]

合併兩個迭代器

4

def ++[B >: A](that :=> GenTraversableOnce[B]): Iterator[B]

合併兩個迭代器

5

def addString(b: StringBuilder): StringBuilder

添加一個字符串到 StringBuilder b

6

def addString(b: StringBuilder, sep: String): StringBuilder

添加一個字符串到 StringBuilder b,並指定分隔符

7

def buffered: BufferedIterator[A]

迭代器都轉換成 BufferedIterator

8

def contains(elem: Any): Boolean

檢測迭代器中是否包含指定元素

9

def copyToArray(xs: Array[A], start: Int, len: Int): Unit

將迭代器中選定的值傳給數組

10

def count(p: (A) => Boolean): Int

返回迭代器元素中滿足條件p的元素總數。

11

def drop(n: Int): Iterator[A]

返回丟棄前n個元素新集合

12

def dropWhile(p: (A) => Boolean): Iterator[A]

從左向右丟棄元素,直到條件p不成立

13

def duplicate: (Iterator[A], Iterator[A])

生成兩個能分別返回迭代器所有元素的迭代器。

14

def exists(p: (A) => Boolean): Boolean

返回一個布爾值,指明迭代器元素中是否存在滿足p的元素。

15

def filter(p: (A) => Boolean): Iterator[A]

返回一個新迭代器 ,指向迭代器元素中所有滿足條件p的元素。

16

def filterNot(p: (A) => Boolean): Iterator[A]

返回一個迭代器,指向迭代器元素中不滿足條件p的元素。

17

def find(p: (A) => Boolean): Option[A]

返回第一個滿足p的元素或None。注意:如果找到滿足條件的元素,迭代器會被置於該元素之後;如果沒有找到,會被置於終點。

18

def flatMap[B](f: (A) => GenTraversableOnce[B]): Iterator[B]

針對迭代器的序列中的每個元素應用函數f,並返回指向結果序列的迭代器。

19

def forall(p: (A) => Boolean): Boolean

返回一個布爾值,指明 it 所指元素是否都滿足p。

20

def foreach(f: (A) => Unit): Unit

在迭代器返回的每個元素上執行指定的程序 f

21

def hasDefiniteSize: Boolean

如果迭代器的元素個數有限則返回true(缺省等同於isEmpty)

22

def indexOf(elem: B): Int

返回迭代器的元素中index等於x的第一個元素。注意:迭代器會越過這個元素。

23

def indexWhere(p: (A) => Boolean): Int

返回迭代器的元素中下標滿足條件p的元素。注意:迭代器會越過這個元素。

24

def isEmpty: Boolean

檢查it是否爲空, 爲空返回 true,否則返回false(與hasNext相反)。

25

def isTraversableAgain: Boolean

Tests whether this Iterator can be repeatedly traversed.

26

def length: Int

返回迭代器元素的數量。

27

def map[B](f: (A) => B): Iterator[B]

將 it 中的每個元素傳入函數 f 後的結果生成新的迭代器。

28

def max: A

返回迭代器迭代器元素中最大的元素。

29

def min: A

返回迭代器迭代器元素中最小的元素。

30

def mkString: String

將迭代器所有元素轉換成字符串。

31

def mkString(sep: String): String

將迭代器所有元素轉換成字符串,並指定分隔符。

32

def nonEmpty: Boolean

檢查容器中是否包含元素(相當於 hasNext)。

33

def padTo(len: Int, elem: A): Iterator[A]

首先返回迭代器所有元素,追加拷貝 elem 直到長度達到 len。

34

def patch(from: Int, patchElems: Iterator[B], replaced: Int): Iterator[B]

返回一個新迭代器,其中自第 from 個元素開始的 replaced 個元素被迭代器所指元素替換。

35

def product: A

返回迭代器所指數值型元素的積。

36

def sameElements(that: Iterator[_]): Boolean

判斷迭代器和指定的迭代器參數是否依次返回相同元素

37

def seq: Iterator[A]

返回集合的系列視圖

38

def size: Int

返回迭代器的元素數量

39

def slice(from: Int, until: Int): Iterator[A]

返回一個新的迭代器,指向迭代器所指向的序列中從開始於第 from 個元素、結束於第 until 個元素的片段。

40

def sum: A

返回迭代器所指數值型元素的和

41

def take(n: Int): Iterator[A]

返回前 n 個元素的新迭代器。

42

def toArray: Array[A]

將迭代器指向的所有元素歸入數組並返回。

43

def toBuffer: Buffer[B]

將迭代器指向的所有元素拷貝至緩衝區 Buffer。

44

def toIterable: Iterable[A]

Returns an Iterable containing all elements of this traversable or iterator. This will not terminate for infinite iterators.

45

def toIterator: Iterator[A]

把迭代器的所有元素歸入一個Iterator容器並返回。

46

def toList: List[A]

把迭代器的所有元素歸入列表並返回

47

def toMap[T, U]: Map[T, U]

將迭代器的所有鍵值對歸入一個Map並返回。

48

def toSeq: Seq[A]

將代器的所有元素歸入一個Seq容器並返回。

49

def toString(): String

將迭代器轉換爲字符串

50

def zip[B](that: Iterator[B]): Iterator[(A, B)

返回一個新迭代器,指向分別由迭代器和指定的迭代器 that 元素一一對應而成的二元組序列

 

9. Trait(特徵)

Scala Trait(特徵) 相當於 Java 的接口,實際上它比接口還功能強大。

與接口不同的是,它還可以定義屬性和方法的實現。

一般情況下Scala的類只能夠繼承單一父類,但是如果是 Trait(特徵) 的話就可以繼承多個,從結果來看就是實現了多重繼承。

Trait(特徵) 定義的方式與類類似,但它使用的關鍵字是 trait,如下所示:

trait Equal {
  def isEqual(x: Any): Boolean
  def isNotEqual(x: Any): Boolean = !isEqual(x)
}

以上Trait(特徵)由兩個方法組成:isEqual 和 isNotEqual。isEqual 方法沒有定義方法的實現,isNotEqual定義了方法的實現。子類繼承特徵可以實現未被實現的方法。所以其實 Scala Trait(特徵)更像 Java 的抽象類。

以下演示了特徵的完整實例:

/* 文件名:Test.scala
 * author:菜鳥教程
 * url:www.runoob.com
 */

trait Equal {
  def isEqual(x: Any): Boolean
  def isNotEqual(x: Any): Boolean = !isEqual(x)
}

class Point(xc: Int, yc: Int) extends Equal {
  var x: Int = xc
 
var y: Int = yc
 
def isEqual(obj: Any) =
    obj.isInstanceOf[Point] &&
    obj.asInstanceOf[Point].x == x
}

object Test {
   def main(args: Array[String]) {
      val p1 = new Point(2, 3)
      val p2 = new Point(2, 4)
      val p3 = new Point(3, 3)

println(p1.isNotEqual(p2))
      println(p1.isNotEqual(p3))
      println(p1.isNotEqual(2))
   }
}

執行以上代碼,輸出結果爲:

$ scalac Test.scala
$ scala
Test
false
true
true

 

特徵構造順序

特徵也可以有構造器,由字段的初始化和其他特徵體中的語句構成。這些語句在任何混入該特徵的對象在構造時都會被執行。

構造器的執行順序:

  1. 調用超類的構造器;
  2. 特徵構造器在超類構造器之後、類構造器之前執行;
  3. 特徵由左到右被構造;
  4. 每個特徵當中,父特徵先被構造;
  5. 如果多個特徵共有一個父特徵,父特徵不會被重複構造
  6. 所有特徵被構造完畢,子類被構造。
  7. 構造器的順序是類的線性化的反向。線性化是描述某個類型的所有超類型的一種技術規格。

 

10. 模式匹配

object Test {
   def main(args: Array[String]) {
      println(matchTest("two"))
      println(matchTest("test"))
      println(matchTest(1))
      println(matchTest(6))

}
   def matchTest(x: Any): Any = x match {
      case 1 => "one"
      case "two" => 2
      case y: Int => "scala.Int"
      case _ => "many"
   }
}

 

11. 正則表達式

import scala.util.matching.Regex

 

object Test {

   def main(args: Array[String]) {

      val pattern = "Scala".r

      val str = "Scala is Scalable and cool"

     

      println(pattern findFirstIn str)

   }

}

12. 異常處理

import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException

object Test {
   def main(args: Array[String]) {
      try {
         val f = new FileReader("input.txt")
      } catch {
         case ex: FileNotFoundException =>{
            println("Missing file exception")
         }
         case ex: IOException => {
            println("IO Exception")
         }
      }
   }
}

 

13. 提取器(Extractor)

提取器是從傳遞給它的對象中提取出構造該對象的參數。

Scala 標準庫包含了一些預定義的提取器,我們會大致的瞭解一下它們。

Scala 提取器是一個帶有unapply方法的對象。unapply方法算是apply方法的反向操作:unapply接受一個對象,然後從對象中提取值,提取的值通常是用來構造該對象的值。

以下實例演示了郵件地址的提取器對象:

object Test {
   def main(args: Array[String]) {
     
      println
("Apply 方法 : " + apply("Zara", "gmail.com"));
      println ("Unapply 方法 : " + unapply("[email protected]"));
      println ("Unapply 方法 : " + unapply("Zara Ali"));

}
   // 注入方法 (可選)
   def apply(user: String, domain: String) = {
      user +"@"+ domain
  
}

// 提取方法(必選)
   def unapply(str: String): Option[(String, String)] = {
      val parts = str split "@"
      if (parts.length == 2){
         Some(parts(0), parts(1))
      }else{
         None
      }
   }
}

執行以上代碼,輸出結果爲:

$ scalac Test.scala
$ scala
Test
Apply 方法 : Zara@gmail.com
Unapply 方法 : Some((Zara,gmail.com))
Unapply 方法 : None

以上對象定義了兩個方法: apply 和 unapply 方法。通過 apply 方法我們無需使用 new 操作就可以創建對象。所以你可以通過語句 Test("Zara", "gmail.com") 來構造一個字符串 "[email protected]"。

unapply方法算是apply方法的反向操作:unapply接受一個對象,然後從對象中提取值,提取的值通常是用來構造該對象的值。實例中我們使用 Unapply 方法從對象中提取用戶名和郵件地址的後綴。

實例中 unapply 方法在傳入的字符串不是郵箱地址時返回 None。代碼演示如下:

unapply("[email protected]") 相等於 Some("Zara", "gmail.com")
unapply("Zara Ali") 相等於 None

 

提取器使用模式匹配

在我們實例化一個類的時,可以帶上0個或者多個的參數,編譯器在實例化的時會調用 apply 方法。我們可以在類和對象中都定義 apply 方法。

就像我們之前提到過的,unapply 用於提取我們指定查找的值,它與 apply 的操作相反。 當我們在提取器對象中使用 match 語句是,unapply 將自動執行,如下所示:

object Test {
   def main(args: Array[String]) {
     
      val x
= Test(5)
      println(x)

x match
     
{
         case Test(num) => println(x + " 是 " + num + " 的兩倍!")
         //unapply 被調用
         case _ => println("無法計算")
      }

}
   def apply(x: Int) = x*2
   def unapply(z: Int): Option[Int] = if (z%2==0) Some(z/2) else None
}

執行以上代碼,輸出結果爲:

$ scalac Test.scala
$ scala
Test
10
10 5 的兩倍!

 

14. I/O

Scala 進行文件寫操作,直接用的都是 java中 的 I/O 類 (java.io.File):

import java.io._

object Test {
   def main(args: Array[String]) {
      val writer = new PrintWriter(new File("test.txt" ))

writer.write("菜鳥教程")
      writer.close()
   }
}

執行以上代碼,會在你的當前目錄下生產一個 test.txt 文件,文件內容爲"菜鳥教程":

$ scalac Test.scala
$ scala
Test
$ cat test.txt
菜鳥教程

 

從屏幕上讀取用戶輸入

有時候我們需要接收用戶在屏幕輸入的指令來處理程序。實例如下:

import scala.io._
object Test {
   def main(args: Array[String]) {
      print("請輸入菜鳥教程官網 : " )
      val line = StdIn.readLine()

println("謝謝,你輸入的是: " + line)
   }
}

Scala2.11 後的版本 Console.readLine 已廢棄,使用 scala.io.StdIn.readLine() 方法代替。

執行以上代碼,屏幕上會顯示如下信息:

$ scalac Test.scala
$ scala
Test
請輸入菜鳥教程官網 : www.runoob.com
謝謝,你輸入的是: www.runoob.com

 

從文件上讀取內容

從文件讀取內容非常簡單。我們可以使用 Scala 的 Source 類及伴生對象來讀取文件。以下實例演示了從 "test.txt"(之前已創建過) 文件中讀取內容:

import scala.io.Source

object Test {
   def main(args: Array[String]) {
      println("文件內容爲:" )

Source.fromFile("test.txt" ).foreach{
         print
      }
   }
}

執行以上代碼,輸出結果爲:

$ scalac Test.scala
$ scala
Test
文件內容爲:
菜鳥教程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章