0

我正在尝试弄清楚如何在 Scala 中使用 Akka。我做对了吗,我需要做的不是这个:

class Class1 {
  def someMethod1 = {
    //.... some operations....
    "someStringData"
  }

  def someMethod2(param1: Int, param2: Double, param3: BigInt) = {
    //.... some operations....
    new someClass
  }
}

//.............................
object Application extends App {
  val c = new Class1
  val stringData = c.someMethod1
  val someClass = c.someMethod2
} 

我必须这样做:

case object SomeMethod
case class SomeClass(a: Int, b: Double, c: BigInt)
case class SomeReturnClass(d: Boolean)

class Class1 extends Actor{
  def receive = {
    case SomeMethod => {
      //.... some operation....
      sender ! "someStringData"
    }

    case SomeClass(a, b, c) => {
     //...some operations....
     val result: Boolean = ..... // some operations.... 
     sender ! new SomeReturnClass(result)
    }
  }
}

//.............................

object Application extends App {
  val system = ActorSystem("HelloSystem")
  val helloActor = system.actorOf(Props[Class1], name = "helloactor")
  val stringData: String = helloActor ! someMethod1
  val someClass: SomeReturnClass = helloActor ! someMethod2
}
4

1 回答 1

3

您的基本想法是正确的,唯一的错误在于您如何尝试获得演员的答案:为此,请查看询问模式。演员在某种意义上就像“活动对象”,但并不是每个对象都应该翻译成演员;在实现 Actor 时使用普通对象组合并不少见。

于 2013-07-21T18:42:50.383 回答