scala進階12-複合類型

trait Compound_Type1
trait Compound_Type2
class Compound_Type extends Compound_Type1 with Compound_Type2

object  Compound_Type {
  //參數x是複合類型,即是type1的類型也是type2的類型
  def compound_Type(x: Compound_Type1 with Compound_Type2) = {
    println("compound type in globle method")
  }

  def main(args: Array[String]): Unit = {
    //函數調用時也必須是複合類型
    compound_Type(new Compound_Type1 with Compound_Type2)

    //傳入非匿名對象
    object compound_Type_object extends Compound_Type1 with Compound_Type2
    compound_Type(compound_Type_object)

    //用type定義別名(引用),使代碼更優雅
    type compound_Type_Alias = Compound_Type1 with Compound_Type2
    def compound_Type_Local(x: compound_Type_Alias) = println("compound type in local method")
    val compound_Type_Class = new Compound_Type
    compound_Type_Local(compound_Type_Class)

    //複合類型和結構類型共用
    type Scala = Compound_Type1 with Compound_Type2 { def init(): Unit }
  }
}

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