【问题标题】:Is there a way to get ArrowAssoc work in pattern matching?有没有办法让 ArrowAssoc 在模式匹配中工作?
【发布时间】:2012-03-15 18:24:27
【问题描述】:

例如,如果我想写

1 -> 2 match {
  case 1 -> 2 => "matched"
  case _      => "not matched"
}
// error: not found: value ->

而不是稍微不那么明显

1 -> 2 match {
  case (1, 2) => "matched"
  case _      => "not matched"
}

【问题讨论】:

    标签: scala pattern-matching


    【解决方案1】:

    我就是有这样的东西!我喜欢它,因为我发现它在许多情况下更具可读性。

    object -> {
      def unapply[A, B](pair: (A, B)): Option[(A, B)] =
        Some(pair)
    }
    

    现在你可以这样做了:

    scala> val a -> b = 1 -> 2
    a: Int = 1
    b: Int = 2
    

    【讨论】:

    • 酷,让我们把它添加到 Predef!
    • 我在一个包含许多此类提取器的文件中都有它,我包含在我的所有项目中,但 Predef 会更方便! (我有几个像这样的文件,包括一个隐含地向集合添加一堆方法的文件。)
    猜你喜欢
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 2015-09-20
    • 2020-01-10
    相关资源
    最近更新 更多