Scala - 启动一个特征?
Scala - Initiating a trait?
有这个代码:
// 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()
}
}
我真的很想知道为什么允许使用 new Eval()
启动 trait Eval
类型,就像 class?
您正在实例化一个匿名 class,即没有名称的 class:
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
}
现在你有两个匿名 classes 并且每个都有不同的 eval
方法实现,注意匿名意味着你不能实例化一个新的 firstEval
或secondEval
。在您的特定情况下,您有一个方法总是 returns 一个匿名 class 具有与该 eval
方法相同的实现。
有这个代码:
// 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()
}
}
我真的很想知道为什么允许使用 new Eval()
启动 trait Eval
类型,就像 class?
您正在实例化一个匿名 class,即没有名称的 class:
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
}
现在你有两个匿名 classes 并且每个都有不同的 eval
方法实现,注意匿名意味着你不能实例化一个新的 firstEval
或secondEval
。在您的特定情况下,您有一个方法总是 returns 一个匿名 class 具有与该 eval
方法相同的实现。