2016-12-08 71 views
2

我有一個演員,我需要做的基於消息hierarhy事案件之間共享邏輯。你可以看到,updateOneAndTwoLogic()調用兩次:從Java API如何在模式匹配

class MyActor extends Actor { 

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

UntypedActor,我可以這樣做:

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()不重複。

如何刪除scala版本中的重複調用?

回答

8

您可以在Scala中使用|語法進行模式匹配。

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

建議

用例對象,而不是case類的空括號。