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

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

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

object Structural__Type {

  def main(args: Array[String]){
    init(new { def open()=println("Opened") }) //创建了一个匿名对象,实现open方法
    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")} } //创建的单例对象里面也必须实现open方法
    init(A)
    
    val structural = new Structural
    init(structural)
    
  }

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

Scala复合类型解析:

trait Compound_Type1; 
trait Compound_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")} //限制参数x即是Type1的类型,也是Type2的类型
  def main(args: Array[String]) {
    
    compound_Type(new Compound_Type1 with Compound_Type2) //匿名方式,结果:Compound Type in global method
    object compound_Type_oject extends Compound_Type1 with Compound_Type2 //object继承方式,trait混入object对象中
    compound_Type(compound_Type_oject) //结果都一样,Compound Type in global method
    
    type compound_Type_Alias = Compound_Type1 with Compound_Type2 //定义一个type别名
    def compound_Type_Local(x:compound_Type_Alias) = println("Compound Type in local method") //使用type别名进行限制
    val compound_Type_Class = new Compound_Type
    compound_Type_Local(compound_Type_Class) //结果:Compound Type in local method
    
    type Scala = Compound_Type1 with Compound_Type2 { def init():Unit } //type别名限制即是Type1,也是Type2,同时还要实现init方法
  }
}

你可能感兴趣的:(Scala结构类型与复合类型解析)