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

本文介绍了Scala中的结构类型和复合类型的使用方法。通过实例展示了如何定义和使用结构类型来指定参数的行为,以及如何通过复合类型来组合多个特质,限制参数必须具备多种特质的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

结构类型:定义方法或者表达式时,要求传参具有某种行为,但又不想使用 类,或者接口去限制可以使用结构类型

点击(此处)折叠或打开

  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博客 ” ,链接:http://blog.itpub.net/28912557/viewspace-1980424/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/28912557/viewspace-1980424/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值