我是akka的初学者,我遇到了这个编译问题:
class MyActor extends Actor {
def receive = {
case Outer(operation, someInt, someBool) =>
makeOperation(operation, someInt, someBool)
}
private def makeOperation(operation: Operation, someInt: Int, someBool: Boolean): Receive = {
operation match {
case MainOp(otherInt) =>
if (someBool) {
if (otherInt < someInt) {
root ! makeMessage(...)
} else if (otherInt > someInt) {
root ! makeMessage(...) // <- compilation error here
} else {
root ! makeMessage(...) // <- compilation error here
}
} else {
if (otherInt > someInt) {
root ! makeMessage(...) // <- compilation error here
} else if (otherInt < someInt) {
root ! makeMessage(...) // <- compilation error here
} else {
root ! makeMessage(...) // <- compilation error here
}
}
case OtherOp1(...) => ???
case OtherOp2(...) => ???
}
}
}
此处控制台显示错误:
MyFile.scala:161: type mismatch;
found : Unit
required: MyActor.this.Receive
(which expands to) PartialFunction[Any,Unit]
root ! makeMessage(...)
^
6 errors found
(assignment/compile:compile) Compilation failed
[error] Total time: 108 s, completed Dec 19, 2013 9:07:46 PM
我该如何解决这个问题?
答案 0 :(得分:2)
替换此行:
private def makeOperation(...): Receive = {
有了这个:
private def makeOperation(...): Unit = {
您的表达式operation match { ... }
的结果类型为Unit
,因为它是每个早午餐中最后一个方法(!
)的结果类型。
方法makeOperation
命名错误。它真正做的是处理消息。
实际上你根本不需要这种方法 - 你可以像这样处理normal
中的消息:
val normal: Receive = {
case Outer(MainOp(otherInt), someInt, true)
if otherInt < someInt => root ! makeMessage(...)
case Outer(MainOp(otherInt), someInt, true)
if otherInt > someInt => ...
case Outer(MainOp(otherInt), someInt, true) => ...
case Outer(MainOp(otherInt), someInt, false)
if otherInt < someInt => ...
case Outer(MainOp(otherInt), someInt, false)
if otherInt > someInt => ...
case Outer(MainOp(otherInt), someInt, false) => ...
case Outer(OtherOp1(...), someInt, someBool) => ...
case Outer(OtherOp2(...), someInt, someBool) => ...
}
只有当您想要更改下一个消息(以及之后的所有消息)的演员行为时,您才需要一个结果类型为Receive
的方法:
context become createNewBehavior(params)
请参阅以下答案以获取示例:
Initializing an actor before being able to handle some other messages
How to properly use akka actors in scala
Is it possible to do that in Scala (without mutating the internal state of a class)?