您的位置:首页 > 其它

Scala进阶源码实战之七——链式调用、结构类型

2016-04-21 20:34 357 查看
链式调用风格

//核心就在 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 }
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: