Scala - Initiating a trait?

牧云@^-^@ 提交于 2019-12-12 03:16:18

问题


There is this code:

// Initial object algebra interface for expressions: integers and addition
trait ExpAlg[E] {
    def lit(x : Int) : E 
    def add(e1 : E, e2 : E) : E
}

// An object algebra implementing that interface (evaluation)

// The evaluation interface
trait Eval {
    def eval() : Int
}

// The object algebra
trait EvalExpAlg extends ExpAlg[Eval] {
    def lit(x : Int) = new Eval() {
        def eval() = x
    }

    def add(e1 : Eval, e2 : Eval) = new Eval() {
        def eval() = e1.eval() + e2.eval()
    }
}

I really would like to know why it is allowed to initiate the trait Eval type with new Eval() like being a class?


回答1:


You are instantiating an anonymous class, that is a class which doesn't have a name:

trait ExpAlg[E] {
  def lit(x : Int) : E
  def add(e1 : E, e2 : E) : E
}

trait Eval {
  def eval() : Int
}

val firstEval = new Eval {
  override def eval(): Int = 1
}

val secondEval = new Eval {
  override def eval(): Int = 2
}

now you have two anonymous classes and each has a different implementation for the eval method, note that being anonymous means that you can't instantiate a new firstEval or secondEval. In your specific case you have a method that always returns an anonymous class with the same implementation of that eval method.



来源:https://stackoverflow.com/questions/28191975/scala-initiating-a-trait

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!