链式调用风格
//核心就在 this.type
class Animal { def breathe: this.type = this }
class Cat extends Animal { def eat : this.type = this }
object Singleton_Types {
def main(args: Array[String]): Unit = {
val cat = new Cat
cat.breathe.eat
}
}
结构类型
鸭子类型
class Structural { def open()=print("A class instance Opened") }
object Structural__Type {
def main(args: Array[String]){
init(new { def open()=println("Opened") })
//type 把等号后面的内容命名为一个别名
type X = { def open():Unit }
def init(res:X) = res.open
init(new { def open()=println("Opened again") })
object A { def open() {println("A single object Opened")} }
init(A)
val structural = new Structural
init(structural)
}
//只要存在 open方法的 类型即可
def init( res: {def open():Unit} ) {
res.open
}
}
复合类型
trait Compound_Type1;
trait Compound_Type2;
//必须同时满足 type1 和type2
class Compound_Type extends Compound_Type1 with Compound_Type2
object Compound_Type {
def compound_Type(x: Compound_Type1 with Compound_Type2) = {println("Compound Type in global method")}
def main(args: Array[String]) {
compound_Type(new Compound_Type1 with Compound_Type2)
object compound_Type_oject extends Compound_Type1 with Compound_Type2
compound_Type(compound_Type_oject)
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 }
}
}