我正在尝试掌握Scala的actors(Akka),但我刚刚遇到了一些奇怪的“case”用法,我不理解:
import akka.actor.{ ActorRef, ActorSystem, Props, Actor, Inbox }
import scala.concurrent.duration._
case object Greet
case class WhoToGreet(who: String)
case class Greeting(message: String)
class Greeter extends Actor {
var greeting = ""
def receive = {
case WhoToGreet(who) => greeting = s"hello, $who"
case Greet => sender ! Greeting(greeting) // Send the current greeting back to the sender
}
}
这部分内容:
def receive = {
case WhoToGreet(who) => greeting = s"hello, $who"
case Greet => sender ! Greeting(greeting) // Send the current greeting back to the sender
}
现在我认为Scala中的案例语法如下:
something match {
case "val1" => println("value 1")
case "val2" => println("value 2")
}
如果我想在Scala REPL中复制这个问题的用法,就像这样:
def something = {
case "val1" => println("value 1")
case "val2" => println("value 2")
}
我明白了
error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
这是什么意思呢?
更新: 这篇文章目前是回答我问题的最佳答案:http://blog.bruchez.name/2011/10/scala-partial-functions-without-phd.html
match
可以解决问题,但我的问题仍然存在 - 为什么在Akka示例中不使用match
也能工作?我在网上找不到任何关于这种语法的参考资料。 - Caballeroreceive
一起工作的原因是您正在覆盖它并且父类型Actor
定义了函数的类型,这是一个PartialFunction...
。要定义自己的部分函数,您只需要定义正确的返回类型(PartialFunction)。有关示例,请参见文档:http://www.scala-lang.org/api/2.10.3/index.html#scala.PartialFunction - yǝsʞǝla