Scala 特征语法 [英] Scala trait syntax
问题描述
我正在阅读 Odersky 的书,并且有一个包含以下代码部分的电子表格示例:
I am reading Odersky's book and there is a speadsheet example with the follwowing code part:
package org.stairwaybook.scells
trait Arithmetic { this: Evaluator =>
operations += (
"add" -> { case List(x, y) => x + y },
"sub" -> { case List(x, y) => x - y },
"div" -> { case List(x, y) => x / y },
"mul" -> { case List(x, y) => x * y },
"mod" -> { case List(x, y) => x % y },
"sum" -> { xs => (0.0 /: xs)(_ + _) },
"prod" -> { xs => (1.0 /: xs)(_ * _) }
)
}
this: Evaluator"指的是什么?有人可以帮助理解这个特征吗?正如我所见,它定义了不同的操作,它们是函数,但我看不到大图...
what does "this: Evaluator" refer to? Could someone help to understand this trait? As I see it defines different operations which are functions, but I do not see the big picture...
推荐答案
你在这里看到的
this:Evaluator =>
是 self-type 对 trait 的用法.它基本上强制将要混合特征算术的类也混合特征评估器.
is the usage of self-type for a trait. It basically forces class which are going to mix the trait Arithmetic to also mix the trait Evaluator.
如果您尝试创建如下所示的类:
If you try to create a class such as the following:
class ArithmeticClass extends Arithmetic
你会得到一个编译时错误,而如果你尝试这样做:
you'll get a compile time error, while if you try to do:
class ArithmeticClass extends Arithmetic with Evaluator
这会奏效.如您所见,Arithmetic 类修改了向操作添加的内容,这可能是 Evaluator trait 中定义的集合.
this is going to work. As you can see, Arithmetic class modifies add something to operations, which is probably a collection defined in the Evaluator trait.
请注意,与简单继承相比,自类型可以让您设计更清晰的类层次结构:
Please note that self-types let you design a cleaner class hierarchy compared to simple inheritance:
如果你使用 self 类型,你可以考虑如下:
If you use self types, you can think about something like the following:
trait Evaluator { def runEvaluation : Int }
trait Arithmetic { self: Evaluator => def evaluate: Int = runEvaluation }
trait NullEvaluator extends Evaluator { def runEvaluation: Int = 0 }
class MyClass1 extends Arithmetic with Evaluator {... concrete methods .... }
class MyClass2 extends Arithmetic with NullEvaluator { ....concrete methods ..... }
所以 self 类型可以让你表达与继承不同的东西.
So self types let you express something different from inheritance.
这篇关于Scala 特征语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!