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 } } }
相关文章推荐
- php干不了的活
- c#重写TabControl控件实现关闭按钮的方法
- differences in python 2 and python 3
- 百度地图api为标注设置与删除文字标签
- 你最喜欢做什么--兴趣问题清单
- Dism 错误 14099
- 对Xabber源码解析的过程(2)connection
- 冲刺3
- SQL Server 分组后取Top N
- 自定义排序数组二分法插入实现
- Spark SQL
- linux命令复制指定文件或者指定目录下的全部文件到另一个目录中
- hive inser into 与 hive overwrite区别
- 兴趣问题清单
- 站内邮件的设计思路
- java基础算法之递推
- Java 锁的学习
- 数据结构求一个矩阵的马鞍点
- 使用 P3P 规范让 IE 跨域接受第三方 cookie
- HDU 2820 Permutaion