部分函数匹配的对象的引用是什么?

时间:2017-01-20 16:01:57

标签: scala pattern-matching partialfunction

以此函数为例:

def receive = {
  case "test" => log.info("received test")
  case _      => log.info("received unknown message")
}

匹配什么对象?在箭头的右侧,我如何引用匹配的对象?

2 个答案:

答案 0 :(得分:4)

你可以使用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"

请注意,如果您有一个想要引用的对象,那么例如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"

答案 1 :(得分:0)

如果您希望案例与任何内容匹配,并且引用它,请使用变量名而不是下划线

def receive = {
  case "test" => log.info("received test")
  case other  => log.info("received unknown message: " + other)
}