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

來源:互聯網
上載者:User

標籤:scala

1.Tuple和List一樣都是不可變對象(immutalbe),但是Tuple的元素可以是不同的類型

    val myTuple = ("A", 1, "park", 3.13359 )    println(myTuple._1 )  // A    println(myTuple._2)  // 1    println(myTuple._3)  // park

建立Tuple只需把元素放在括弧裡面就可以了,上面建立了一個Tuple4類的執行個體,Tuple4在scala中的定義是這樣的

/** A tuple of 4 elements; the canonical representation of a [[scala.Product4]]. * *  @constructor  Create a new tuple with 4 elements. Note that it is more idiomatic to create a Tuple4 via `(t1, t2, t3, t4)` *  @param  _1   Element 1 of this Tuple4 *  @param  _2   Element 2 of this Tuple4 *  @param  _3   Element 3 of this Tuple4 *  @param  _4   Element 4 of this Tuple4 */@deprecatedInheritance("Tuples will be made final in a future version.", "2.11.0")case class Tuple4[+T1, +T2, +T3, +T4](_1: T1, _2: T2, _3: T3, _4: T4)  extends Product4[T1, T2, T3, T4]{  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + ")"  }

類似5個元素的Tuple是Tuple5的執行個體,6個元素的Tuple是Tuple6的執行個體

因此就可以解釋為什麼會用 _1, _2, _3等來引用Tuple中的元素了

Tuple4定義中的型別參數前面有 + 號,這個代表 covarience參數,以後會深入講解

2. Set有兩類, 不可變的和可變的,名字相同,預設建立不可變的Set對象

650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/55/46/wKiom1SJYMeBdQOaAAF8Nvro-Is758.jpg" title="2014-12-11 17_15_07-Programming in Scala, 2nd Edition.pdf - Foxit Reader.png" alt="wKiom1SJYMeBdQOaAAF8Nvro-Is758.jpg" />

    var jetSet = Set("Bench", "Audi", "Tesilla")    jetSet += "LuHu"    println(jetSet.contains("Bicycle"))


To add a new element to a set, you call + on the set, passing in the new element. Both mutable and immutable sets offer a + method, but their behavior

differs. Whereas a mutable set will add the element to itself, an immutable

set will create and return a new set with the element added

對於immutable的Set ,+ 運算建立一個新的Set

對於mmutalbe的Set, +運算添加元素到它自己


3. Map與Set類似,也有immuatlbe和mutable兩種實現

4. 讀取檔案

import scala.io.Sourceobject TestMain {  def main(args: Array[String]) {  var lines = Source.fromFile("E:/testRead.txt").getLines  lines.foreach(println)  }}


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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.