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

本文深入探讨Scala编程中的链式调用技巧与结构类型的运用,包括其工作原理和实际应用。通过理解鸭子类型的概念,进一步揭示了Scala中复合类型如何增强代码的灵活性和可读性。

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

链式调用风格

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

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值