【问题标题】:What is the reference of the object that a partial function matches on?部分函数匹配的对象的引用是什么?
【发布时间】:2017-06-05 16:25:07
【问题描述】:

以这个函数为例:

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

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

【问题讨论】:

    标签: scala pattern-matching partialfunction


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果您希望大小写匹配任何内容并引用它,请使用变量名而不是下划线

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-11
        • 1970-01-01
        • 1970-01-01
        • 2012-01-23
        • 1970-01-01
        • 2011-11-09
        • 2017-06-21
        相关资源
        最近更新 更多