2016-03-01 66 views
1

我有延伸演員如何從Actor類繼承受保護的函數?

class foo extends Actor{ 
    def receive:PartialFunction[Any, Unit] = ??? 

    protected def fooFunctionIWant = { print("hello")} 
} 

類Foo和我有另一個類「酒吧」,我想延長富所以它會繼承fooFunctionIWant

但是當我嘗試:

object bar extends foo { 
    def barFunc = { 
    fooFunctionIWant 
    } 

} 

然後:

bar.barFunc 

我得到:

Caused by: akka.actor.ActorInitializationException: You cannot create an instance of [...] explicitly using the constructor (new). You have to use one of the 'actorOf' factory methods to create a new actor. See the documentation. 
    at akka.actor.ActorInitializationException$.apply(Actor.scala:173) ~[akka-actor_2.11-2.4.1.jar:na] 
    at akka.actor.Actor$class.$init$(Actor.scala:436) ~[akka-actor_2.11-2.4.1.jar:na] 
+0

你是用'new'還是'actorOf'創造一個演員? –

+0

我所做的是我打電話給(新酒吧).barFunc,然後我得到錯誤。對不起,我將編輯我的問題.. –

+1

你不應該用'new'創建Actor,這就是爲什麼你會得到這個錯誤 –

回答

1

創建actor實例的唯一正確方法是使用actorOf方法之一。在運行時使用new Actorobject Actor將失敗。

您不能直接調用actor中的任何方法,只能向其發送消息並從中接收消息。否則,如果這可能會破壞Actor封裝。

如果你想在一個actor和一個普通類之間共享代碼,你可以把這個共享代碼放在一個trait中並從中繼承。但是,您的演員只能在內部使用該代碼,並且不會公開任何方法,但從actorOf返回的實例類型仍將僅爲Actor

+1

謝謝你的回答:) –