[英]Scala trait syntax
我正在閱讀 Odersky 的書,並且有一個帶有以下代碼部分的電子表格示例:
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”指的是什么? 有人可以幫助理解這個特征嗎? 正如我所見,它定義了不同的操作,它們是函數,但我看不到大圖......
你在這里看到的
this:Evaluator =>
是 self-type 用於 trait 的用法。 它基本上強制將要混合特征算術的類也混合特征評估器。
如果您嘗試創建一個類,如下所示:
class ArithmeticClass extends Arithmetic
你會得到一個編譯時錯誤,而如果你嘗試這樣做:
class ArithmeticClass extends Arithmetic with Evaluator
這是行得通的。 如您所見,Arithmetic 類修改了向操作添加的內容,這可能是在 Evaluator trait 中定義的集合。
請注意,與簡單繼承相比,自類型可以讓您設計更清晰的類層次結構:
如果您使用 self 類型,您可以考慮以下內容:
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 類型讓你表達與繼承不同的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.