ITPub博客

首页 > 应用开发 > Java > Scala结构类型与复合类型解析

Scala结构类型与复合类型解析

原创 Java 作者:541732025 时间:2016-01-21 21:11:03 0 删除 编辑
结构类型:定义方法或者表达式时,要求传参具有某种行为,但又不想使用类,或者接口去限制,可以使用结构类型。

点击(此处)折叠或打开

  1. class Structural { def open()=print("A class instance Opened") }

  2. object Structural__Type {

  3.   def main(args: Array[String]){
  4.     init(new { def open()=println("Opened") }) //创建了一个匿名对象,实现open方法
  5.     type X = { def open():Unit } //将右边的表达式命名为一个别名
  6.     def init(res:X) = res.open
  7.     init(new { def open()=println("Opened again") })
  8.     
  9.     object A { def open() {println("A single object Opened")} } //创建的单例对象里面也必须实现open方法
  10.     init(A)
  11.     
  12.     val structural = new Structural
  13.     init(structural)
  14.     
  15.   }

  16.   def init( res: {def open():Unit} ) { //要求传进来的res对象具有open方法,不限制类型
  17.             res.open
  18.         }
  19. }

Scala复合类型解析:

点击(此处)折叠或打开

  1. trait Compound_Type1;
  2. trait Compound_Type2;
  3. class Compound_Type extends Compound_Type1 with Compound_Type2
  4. object Compound_Type {
  5.   def compound_Type(x: Compound_Type1 with Compound_Type2) = {println("Compound Type in global method")} //限制参数x即是Type1的类型,也是Type2的类型
  6.   def main(args: Array[String]) {
  7.     
  8.     compound_Type(new Compound_Type1 with Compound_Type2) //匿名方式,结果:Compound Type in global method
  9.     object compound_Type_oject extends Compound_Type1 with Compound_Type2 //object继承方式,trait混入object对象中
  10.     compound_Type(compound_Type_oject) //结果都一样,Compound Type in global method
  11.     
  12.     type compound_Type_Alias = Compound_Type1 with Compound_Type2 //定义一个type别名
  13.     def compound_Type_Local(x:compound_Type_Alias) = println("Compound Type in local method") //使用type别名进行限制
  14.     val compound_Type_Class = new Compound_Type
  15.     compound_Type_Local(compound_Type_Class) //结果:Compound Type in local method
  16.     
  17.     type Scala = Compound_Type1 with Compound_Type2 { def init():Unit } //type别名限制即是Type1,也是Type2,同时还要实现init方法
  18.   }

  19. }

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28912557/viewspace-1980424/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: Scala路径依赖
请登录后发表评论 登录
全部评论

注册时间:2013-05-23

  • 博文量
    127
  • 访问量
    515714