模式匹配“返回"价值 [英] Pattern Match "return" value

查看:52
本文介绍了模式匹配“返回"价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能链接模式匹配结构?例如,以下是合法的,如果是无意义的,

Why is it not possible to chain pattern matching constructs? For instance, the following is legal, if nonsensical,

val a = ADT(5)

val b = a match {
  case ADT(a) if a > 4 => ADT(a * 3)
  case ADT(a) => ADT(a + 1)
} 
b match {
  case ADT(a) if a > 13 => doSomething(a)
  case _ => {}
}

但以下不是:

a match {
  case ADT(a) if a > 4 => ADT(a * 3)
  case ADT(a) => ADT(a + 1)
} match {
  case ADT(a) if a > 13 => doSomething(a)
  case _ => {}
}

我怀疑这是因为我一开始就不应该这样做,但原则上我不明白为什么它不合法.

I suspect it's because I shouldn't be doing it in the first place, but in principle I don't see why it's not legal.

推荐答案

是的,它应该可以工作,因为(几乎)Scala 中的所有内容都是一个表达式,并且每个表达式都可以用作模式匹配.

Yes it should work, because (almost) everything in Scala is an expression and every expression can be used as a pattern match.

在这种情况下,模式匹配是一个表达式,因此它可以被另一个链式"模式匹配使用.但是编译器不喜欢它.

In this case the pattern match is an expression, so it can be used by another "chained" pattern match. But the compiler doesn't like it.

用括号给编译器一些提示会有所帮助:

Giving the compiler a little hint with parentheses helps:

case class ADT(value: Int)

val a = ADT(5)

(a match {
  case ADT(a) if a > 4 => ADT(a * 3)
  case ADT(a) => ADT(a + 1)
}) match {
  case ADT(a) if a > 13 => println(a)
  case _ => {}
}

这篇关于模式匹配“返回"价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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