问题
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