以这个函数为例:
def receive = {
case "test" => log.info("received test")
case _ => log.info("received unknown message")
}
正在匹配什么对象?在箭头的右侧,我如何引用正在匹配的对象?
以这个函数为例:
def receive = {
case "test" => log.info("received test")
case _ => log.info("received unknown message")
}
正在匹配什么对象?在箭头的右侧,我如何引用正在匹配的对象?
您可以使用 if-guard 来做到这一点:
def receive: String => Unit = {
case str if str == "test" => println(str)
case _ => println("other")
}
Option("test").map(receive) // prints "test"
Option("foo").map(receive) // prints "other"
请注意,如果您有一个要引用的对象,那么诸如 eg 之类的东西foo: Foo(s)
将不起作用(foo: Foo
会,但是您会失去对 Foo 值的引用s
)。在这种情况下,您需要使用@
运算符:
case class Foo(s: String)
def receive: Foo => Unit = {
case foo@Foo(s) => println(foo.s) // could've referred to just "s" too
case _ => println("other")
}
Option(Foo("test")).map(receive) // prints "test"
如果您希望大小写匹配任何内容并引用它,请使用变量名而不是下划线
def receive = {
case "test" => log.info("received test")
case other => log.info("received unknown message: " + other)
}