Scala - 特征扩展

时间:2015-01-25 14:15:53

标签: scala traits

我试图了解Odresky如何通过使用Traits应用(在一个示例中)应用程序功能的扩展,这里是代码:

trait Base {
  type exp <: Exp

  trait Exp {
    def eval: Int
  }

  class Num(v: Int) extends Exp {
    val value = v
    def eval = value
  }
}

trait BasePlus extends Base {
  class Plus(l: exp, r: exp) extends Exp {
    val left = l
    val right = r
    def eval = left.eval + right.eval
  }
}

trait BaseNeg extends Base {
  class Neg(t: exp) extends Exp {
    val term = t
    def eval = -term.eval
  }  
}

trait Show extends Base {
  type exp <: Exp

  trait Exp extends super.Exp {
    def show: String
  }

  class Num(v: Int) extends super.Num(v) with Exp {
    def show = value.toString()
  }
}

trait BasePlusNeg extends BasePlus with BaseNeg

trait ShowPlusNeg extends BasePlusNeg with Show {
  class Plus(l:exp, r: exp) extends super.Plus(l, r) with Exp {
    def show = left.show + "+" + right.show
  }
  class Neg(t: exp) extends super.Neg(t) with Exp {
    def show = "-(" + term.show + ")"
  }
}


trait DblePlusNeg extends BasePlusNeg {
  type exp <: Exp

  trait Exp extends super.Exp {
    def dble: exp
  }

  def Num(v: Int): exp
  def Plus(l: exp, r: exp): exp
  def Neg(t:exp): exp

  class Num(v: Int) extends super.Num(v) with Exp {
    def dble = Num(v * 2)
  }
  class Plus(l: exp, r:exp) extends super.Plus(l, r) with Exp {
    def dble = Plus(left.dble, right.dble)
  }
  class Neg(t: exp) extends super.Neg(t) with Exp {
    def dble = Neg(t.dble)
  }
}

trait ShowDblePlusNeg extends ShowPlusNeg with DblePlusNeg {
  type exp <: Exp
  trait Exp extends super[ShowPlusNeg].Exp with super[DblePlusNeg].Exp
  class Num(v: Int) extends super[ShowPlusNeg].Num(v) with super[DblePlusNeg].Num(v) with Exp //error
  class Plus(l: exp, r: exp) extends super[ShowPlusNeg].Plus(l, r) with super[DblePlusNeg].Plus(l, r) with Exp //error
  class Neg(t: exp) extends super[ShowPlusNeg].Neg(t) with super[DblePlus.Neg].Neg(t) with Exp //error
}

最后三个混音不会编译,因为

 Multiple markers at this line
    - traits or objects may not have parameters
    - class Num needs to be a trait to be mixed in
  • 我猜它是用以前版本的Scala 1.4实现的,但无论如何一个类从来都不能提供混合,也不能在之前的版本中提供。如何在不需要更改Traits中的类的情况下进行混合?

0 个答案:

没有答案