54.Scala中复合类型实战详解

A extends B with C with D
A必须同时是B、C、D的类型。比如某个类既具有某种功能,又能序列化
eg:可以规定List或者Array里的元素, 比如必须实现序列化接口又必须实现某个功能性接口


trait Compound_Type1
trait Compound_Type2
class Compound_Type extends Compound_Type1 with Compound_Type2

object Compound_Type_54 {
    def compound_Type(x : Compound_Type1 with Compound_Type2) = {  //同时是2个类型
      println("Compound Type in global method")
    }
    
    def main(args: Array[String]): Unit = {
      compound_Type(new Compound_Type1 with Compound_Type2)  //new 一个匿名类的实例
      object compound_Type_object extends Compound_Type1 with Compound_Type2  //把trait混入object中
      compound_Type(compound_Type_object)
      
      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  }  //scala类型既是Compound_Type1类型又是Compound_Type2类型又必须实现init()方法
    }
}

输出:

Compound Type in global method
Compound Type in global method
compound Type in local method


参考资料来源于大数据梦工厂 深入浅出scala 第54讲 由王家林老师讲解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值