Programming in Scala (Second Edition) 讀書筆記3

來源:互聯網
上載者:User

標籤:scala

  1. 建立並初始化一個String Array

    val strArr1 = new Array[String](3)    strArr1(0) = "How"    strArr1(1) = "are"    strArr1(2) = "you!"

上述代碼被transform 為

    val strArr1 = new Array[String](3)    strArr1.update(0, "How")    strArr1.update(1, "are")    strArr1.update(2, "you!")

scala doc 中有一下描述:

  /** Update the element at given index.   *   *  Indices start at `0`; `xs.update(i, x)` replaces the i^th^ elemen t in the array.   *  Note the syntax `xs(i) = x` is a shorthand for `xs.update(i, x)`.   *   *  @param    i   the index   *  @param    x   the value to be written at index `i`   *  @throws       ArrayIndexOutOfBoundsException if `i < 0` or `length <= i`   */  def update(i: Int, x: T) { throw new Error() }

2.  使用伴隨對象(companion object)建立並初始化Array

   

val strArr2 = Array("Fine", "thank", "you")

這裡Array是一個對象的名字,在Scala中對象出現在函數的位置的時候,比如這裡,對象後面跟了括弧,scala的編譯器就會自動尋找這個對象的apply方法,所以這裡調用的其實是Array.apply

在scala 源碼中可以看到

  // Array(e0, ..., en) is translated to { val a = new Array(3); a(i) = ei; a }  def apply[T: ClassTag](xs: T*): Array[T] = {    val array = new Array[T](xs.length)    var i = 0    for (x <- xs.iterator) { array(i) = x; i += 1 }    array  }

apply方法為我們建立了類Array的一個對象,並初始化。這裡的object Array就是class Array的伴隨對象。


3. 同理

    val strArr = Array("Fine", "thank", "you")println(strArr(0))  // strArr(0) 本質上調用的是 strArr.apply

4. 在Array 是可變類型, List是不可變類型。 List的使用樣本

    val twoThree = List(2, 3)    val oneTwoThree = 1 :: twoThree  // 這裡 :: List的一個方法, 在Scala中所有的操作符(operator)都是方法,且以冒號結尾的操作符為右操作符(參數在左邊,對象在右邊)     println(oneTwoThree)  // List(1, 2, 3)

也可以這樣

  val oneTwoThree = 1 :: 2 :: 3 :: Nil  println(oneTwoThree) // List(1, 2, 3)


5. 為什麼不往List的後面添加元素

Why not append to lists?

Class List does offer an “append” operation —it’s written :+ and is

explained in Chapter 24— but this operation is rarely used, because

the time it takes to append to a list grows linearly with the size of the

list, whereas prepending with :: takes constant time. Your options if

you want to build a list efficiently by appending elements is to prepend

them, then when you’re done call reverse; or use a ListBuffer, a

mutable list that does offer an append operation, and when you’re done

call toList. 

追加元素的時間複雜程度會隨元素個數線性增長

可以先向前追加,然後reverse

或先使用ListBuffer 再toList

    val L12345 = 1 :: 2 :: 3 :: 4 :: 5 :: Nil    val L54321 = L12345.reverse    print(L54321)  // List(5, 4, 3, 2, 1)
import scala.collection.mutable.ListBufferobject TestMain {  def main(args: Array[String]) {        val lb = new ListBuffer[Int]    lb.append(1)    lb.append(2)    lb.append(3)        var l = lb.toList    println(l)  // List(1, 2, 3)  }}


6.最後解釋一下 val 和 var

  兩者都是scala中的變數修飾符,如java中的static ,final。 

  val 的作用是正是聲明一個final的變數,即不可再被賦值的變數

  var 與val相反

  另外scala中沒有類似java 的static關鍵字


7.瀏覽一下List的其它方法

List() or Nil
The empty List
List("apple", "banana", "pare") create a new List[String]
"apple" :: "banana" :: "pear" :: Nil 同上
count(s => s.length == 4)
Counts the number of string elements that have length 4 
drop(2) Returns the list without its first 2 elements
dropRight(2) Returns the list without its rightmost 2 elements
exists(s => s=="until") Detemine whether a string element exists in the list
filter(s => s.length == 4) Return a list of all elements, in order, of the list that have lengh 4
forall(s => s.endWith("l")) Indiates whether all elements in  the list end with letter "l"
foreach(s => print(s))
Executes the print statement on each of the string in the list
foreach(print) Same as previous
head The first element
init a list of all but the last element
isEmpty Indicates whether the list is empty
last the last element
length number of elements
map(s => s + "y") Return a list resulting from adding a "y" to each string element in the list
mkString(", ") Makes a string with the elements of the list
remove(s => s.length==4) Return a list containning al elements of the list except those that have length 4
reverse Returns a list in reverse order
sort 
Return a list in alpabetical order
tail Returns the list minus its first element


Programming in Scala (Second Edition) 讀書筆記3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.