3
我想知道爲什麼這個代碼中的akka Actor的接收方法的行爲像一個val?爲什麼在akka中接收Actor方法的行爲像val?
import akka.actor.{ ActorRef, ActorSystem, Props, Actor }
import scala.concurrent.duration._
// Define Actor Messages
case class WhoToGreet(who: String)
// Define Greeter Actor
class Greeter extends Actor {
def receive = {
println("in receive")
receiveHandler
}
def receiveHandler: Receive = {
case WhoToGreet(who) => println(s"Hello $who")
}
}
object HelloAkkaScala extends App {
// Create the 'hello akka' actor system
val system = ActorSystem("Hello-Akka")
// Create the 'greeter' actor
val greeter = system.actorOf(Props[Greeter], "greeter")
// Send WhoToGreet Message to actor
greeter ! WhoToGreet("Akka")
greeter ! WhoToGreet("Akka")
greeter ! WhoToGreet("Akka")
//shutdown actorsystem
system.terminate()
}
輸出:
in receive
Hello Akka
Hello Akka
Hello Akka
,當它被認爲是:
in receive
Hello Akka
in receive
Hello Akka
in receive
Hello Akka
而接收是DEF。
有關這種行爲的任何想法,爲什麼def這裏計算像val?
謝謝,但爲什麼在這[代碼](https://www.jdoodle.com/embed/v0/scala/2.12.0/14e)它的行爲像一個def? – SaKou
您鏈接的代碼與PartialFunctions完全無關,您可以通過將返回類型更改爲Unit來證明這一點。您的方法在PartialFunction之外執行副作用(printlns)。 Akka調用(緩存的)PartialFunction。 –
你可以請,看看上面的代碼,我已經將部分類型更改爲:type Partial = PartialFunction [Any,Unit] 我看不出差異 – SaKou