Scala特征语法
我正在阅读奥德斯基的书,其中有一个speadsheet示例,代码部分如下:Scala特征语法,scala,Scala,我正在阅读奥德斯基的书,其中有一个speadsheet示例,代码部分如下: package org.stairwaybook.scells trait Arithmetic { this: Evaluator => operations += ( "add" -> { case List(x, y) => x + y }, "sub" -> { case List(x, y) => x - y },
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 =>
自我类型是一种特质的用法。它基本上迫使将混合特质算法的类也混合特质评估器
如果尝试创建以下类:
class ArithmeticClass extends Arithmetic
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 ..... }
如果尝试执行以下操作,则会出现编译时错误:
class ArithmeticClass extends Arithmetic with Evaluator
这会有用的。如您所见,算术类修改向操作添加了一些内容,这可能是在Evaluator trait中定义的集合
请注意,与简单继承相比,self类型允许您设计更清晰的类层次结构:
如果使用self类型,您可以考虑以下内容:
class ArithmeticClass extends Arithmetic
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类型可以让您表达与继承不同的东西。这当然是正确的,但通常不会直接混入
Evaluator
(因为在这种情况下,算术
可能只是扩展Evaluator
),而是Evaluator
的子类型。