跟連樂一起學Scala-進階類型,scala-類型

來源:互聯網
上載者:User

跟連樂一起學Scala-進階類型,scala-類型

歡迎加入Scala討論QQ群212859367,和連樂一起討論學習!

單例類型
例子:

class Document{    def setTitile(title: String) = {...; this}    def setAuthor(author: String) = {...; this}    ...}val atticle.setTitle("whatever floats your boat").setAuthor("lianle")

如果以上類有子類,會出現問題:

class Book extends Document{    def addChapter(chapter: String) = {...; this}    ...}//調用出錯:val book = new Bookbook.setTitle("Scala for the impatient").addChapter("chapter1")

分析原因:
由於setTitle返回的是this;Scala將傳回型別推斷為Document,但是Document沒有addChapter方法。

解決方案:

def setTitle(title: String) : this.type = {...; this}//添加單例類型

類型投影
例子:

import scala.collection.mutable.ArrayBufferclass Network {    class Member(val name: String) {        val contacts = new ArrayBuffer[Member]    }    private val members = new ArrayBuffer[Member]    def join(name: String) = {        val m = new Member(name)        members += m        m    }}

定義兩個網路:

val chatter = new Networkval myFace = new Network

如下操作會報錯:

val fred = chatter.join("Fred")  //類型為chatter.Memberval barney = myFace.join("Barney")//類型為myFace.Memberfred.contacts += barney  //報錯

解決方案:

class Network {    class Member(val name: String) {        val contacts = new ArrayBuffer[Network#Member]        //以上意思是:“任何Network的Member”    }}

類型別名

對於複雜類型,你可以使用type關鍵字建立一個別名。

class Book {    import scala.collection.mutable._    type Index = HashMap[String, (Int, Int)]    //之後,可以使用Index來代替HashMap了。}

別名必須被嵌套在類或者對象中。

結構類型

所謂的”結構類型“指的是一組關於抽象方法、欄位和類型的規格說明。這些抽象方法、欄位和類型是滿足該規格的類型必須具備的。

def appedLines(target: {def append(str: String): Any}, lines: Iterable[String]) {    for(l <- lines){ target.append(1);target.append("\n")}}

你可以對任何具備append方法的類的執行個體調用appendLines方法。

複合類型
定義形式:

T1 with T2 with T3 ...

例子:

val image = new ArrayBuffer[java.awt.Shape with java.io.Serializable]
Shape with Serializable {def contains(p: Point):Boolean}//該類型的執行個體必須既是Shape的子類型也是Serializable的子類型。

中置類型

中置類型是一個帶有兩個型別參數的類型。

String Map Int//String 和 Int類型的中置。//類似數學中的A * B

存在類型

存在類型被加入Scala是為了與Java的類型萬用字元相容。
定義形式:在類型運算式之後跟上forSome{…},花括弧中包含了type和val的聲明。

Array[T] forSome{ type T <: JComponent}等價於:Array[_ <: JComponent]
Array[_]等價於:Array[T] forSome{type T}
Map[_, _]等價於:Map[T, U] forSome {type T; type U}

forSome允許我們使用更複雜的關係,而不僅限於類型萬用字元能表達的那些。
Map[T, U] forSome {type T; type U <: T}

Scala類型系統

類型 文法舉例
類或特質 class C…, trait C…
元群組類型 (T1,T2,…Tn)
函數類型 (T1,T2…Tn) => T
帶註解的類型 T@A
參數化型別 A[T1,T2…Tn]
單例類型 值.type
類型投影 O#I
複合類型 T1 with T2 with … with Tn{聲明}
中置類型 T1 A T2
存在類型 T forSome {type 和val 聲明}

自身類型

形式:

this: 類型 => 

舉例:

trait Logged {    def log(msg: String)}trait LoggedException extends Logged {    this: Exception =>    def log(){log(getMessage())}    //可以調用getMessage,因為this是一個Exception}

依賴注入

trait LoggerComponent {    trait Logger {...}    val logger: Logger    class FileLogger(file: String) extends Logger {...}}trait Auth {    this: LoggerComponent => //讓我們可以訪問日誌器    trait Auth{...}    val auth: Auth    class MockAuth(file: String) extends Auth {...}    ...}

組裝配件:

object AppComponents extends LoggerComponent with AuthComponet {    val logger = new FileLogger(text.log)    val auth = new MockAuth("users.txt")}

抽象類別型

類或特質可以定義一個在子類中被具體化的抽象類別型。

trait Reader {    type Contents    def read(fileName: String): Contents}

實現:

class StringReader extends Reader {    type Contents = String    def read(fileName: String)  = Source.fromFile(fileName, "UTF-8").mkString}class ImageReader extends Reader {    type Contents = BufferedImage    def read(fileName: String) = ImageIO.read(new File(fileName))}

另一個例子:

trait Reader[C]{    def read(file: String) : C}class StringReader extends Reader[String] {    def read(fileName: String) = Source.fromFile(fileName, "UTF-8").mkString}class ImageReader extends Reader[BufferdImage] {    def read(fileName: String) = ImageIO.read(new File(fileName))}

經驗:

1.如果類型是在類被執行個體化時給出,則使用型別參數。
2.如果類型是在子類中給出,則適用抽象類別型。

高等類型

泛型型別List依賴於類型T併產生一個特定的類型。
像List這樣的泛型型別有時被稱做類型構造器。
在Scala中,你可以定義出依賴於依賴其他類型的類型的類型。

歡迎加入Scala討論QQ群212859367,和連樂一起討論學習!

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

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