有没有办法让 ArrowAssoc 在模式匹配中工作? [英] Is there a way to get ArrowAssoc work in pattern matching?

查看:61
本文介绍了有没有办法让 ArrowAssoc 在模式匹配中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如如果我想写

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

而不是稍微不那么明显

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

推荐答案

我正好有这样的事情!我喜欢它,因为我发现它在许多情况下更具可读性.

I have just such a thing! I like it because I find it more readable in many cases.

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

这篇关于有没有办法让 ArrowAssoc 在模式匹配中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆