1

この質問は、Akka Concurrencyのプレプリント(最終バージョンはまだ利用できません)に基づいており、説明なしで使用されています。

クラスのバージョン1では、次のようになります。

class Altimeter extends Actor with ActorLogging with EventSource{
...
}

AltimeterはEventSourceと緊密に連携しているため、AltimeterをテストするにはEventSourceもテストする必要があります。修正するための推奨される変更は次のとおりです。

--- a/src/main/scala/Altimeter.scala
+++ b/src/main/scala/Altimeter.scala
@@ -9,9 +9,10 @@ import  scala.concurrent.ExecutionContext.Implicits.global
 object Altimeter{
   case class RateChange(amount: Float) //sent to Altimeter
   case class AltitudeUpdate(altitude: Double)
+  def apply() = new Altimeter with ProductionEventSource
 }

-class Altimeter extends Actor with ActorLogging with EventSource{
+class Altimeter extends Actor with ActorLogging{ this: EventSource =>
   import Altimeter._

   val ceiling = 43000       //feet
diff --git a/src/main/scala/EventSource.scala b/src/main/scala/EventSource.scala
index 1fd5578..ded4f38 100755
--- a/src/main/scala/EventSource.scala
+++ b/src/main/scala/EventSource.scala
@@ -8,7 +8,12 @@ object EventSource{
   case class UnregisterListener(listener: ActorRef)
 }

-trait EventSource { this: Actor =>
+trait EventSource{
+  def sendEvent[T](event: T): Unit
+  def eventSourceReceive: Actor.Receive
+}
+
+trait ProductionEventSource { this: Actor =>
   import EventSource._

私の最初の問題は、何がthis: SomeTraitType =>達成されるのか理解できないことです。クラスはSomeTraitTypeタイプであると文字通り言っていますか?

私の2番目の質問は、それと使用の違いは何extends SomeTraitTypeですか、そしてなぜそれが有利なのですか?前者が意味することを私が知っていれば、おそらくそれは明らかでしょう。

4

1 に答える 1

6

この表記(this: EventSource => ...)は「自己型注釈」と呼ばれ、特性を別の継承構造に混合する方法を制限します。(だけでなく)任意の名前thisを使用できます。selfもう1つの一般的なものです。

この使用法は、多かれ少なかれ、ケーキパターン(またはその簡略化)です。その用語を使用すると、その使用法を説明するのに役立つ多くのリソースを見つけることができます。

自己型アノテーションの別の使用法(通常は制約なし、単純)は、外部がマスクされているネストされたスコープ(ネストされたクラス)で使用できるself => ...エイリアスを作成します。thisthis

于 2013-02-15T22:41:58.393 に答える