有没有办法让 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