2016-12-08 13 views
2

は私がメッセージhierarhyに基づいて何かを必要とする俳優を持っているパターンマッチングでは例の間でロジックを共有することができます。はどのよう

public void onReceive(Object message) { 
    if (message instanceof UpdateMessage) 
     updateOneAndTwoLogic(); 
    if (message instanceof UpdateOne) 
     updateOne(); 
    if (message instanceof UpdateTwo) 
     UpdateTwo(); 
    if (message instanceof Other) 
     ... 
} 

updateOneAndTwoLogic()は繰り返しませんここで、私のような何かを行うことができ、JavaのAPIからUntypedActor

class MyActor extends Actor { 

    def receive: PartialFunction[Any, Unit] = { 
     case UpdateOne() => { 
      updateOneAndTwoLogic() //repeated 
      updateOne() 
     } 
     case UpdateTwo() => { 
      updateOneAndTwoLogic() //repeated 
      updateTwo() 
     } 
     case Other() => { 
      ... 
     } 
    } 
} 

:あなたはupdateOneAndTwoLogic()を2回呼び出していることを、見ることができます。

スカラー版で重複した呼び出しを削除するにはどうすればよいですか?

答えて

8

|の構文は、Scalaのパターンマッチング中に使用できます。

case msg @ (UpdateOne() | UpdateTwo()) => 
    updateOneAndTwoLogic() 
    msg match { 
    case UpdateOne() => updateOne() 
    case UpdateTwo() => updateTwo() 
    } 

提案

ユースケースは、代わりに空の括弧の場合のクラスのオブジェクト。