Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does chaining match expressions does not compile? [duplicate]

Tags:

scala

Chaining match expressions does not compile.

val x = Array("abc", "pqr")

x match {
  case Array("abc", _*) => Some("abc is first")
  case Array("xyz", _*) => Some("xyz is first")
  case _ => None
} match {
  case Some(x) => x
  case _ => "Either empty or incorrect first entry"
}

While the following compiles fine:

(x match {
  case Array("abc", _*) => Some("abc is first")
  case Array("xyz", _*) => Some("xyz is first")
  case _ => None
}) match {
  case Some(x) => x
  case _ => "Either empty or incorrect first entry"
}

Why does the later version (where first match expression is in paranthesis) compile fine while earlier one does not?

like image 619
Shyamendra Solanki Avatar asked Aug 09 '13 14:08

Shyamendra Solanki


1 Answers

If it were allowed, you couldn't do:

scala> List(1,2,3) last match { case 3 => true }
warning: there were 1 feature warning(s); re-run with -feature for details
res6: Boolean = true

That is, if it were infix notation, then the thing to the left could not be postfix.

Disallowing infix match permits a postfix scrutinee.

That expression is parsed the natural way

(List(1,2,3) last) match { case 3 => true }

that is, if postfix notation is natural and not unholy.

The feature warning is for import language.postfixOps. Perhaps with that feature turned off, the Defenders of the Good would be willing to entertain import language.infixMatch.

Consider constructs that are syntactic siblings to match, that are not infixable without parens:

scala> if (true) 1 else 2 match { case 1 => false }
res4: AnyVal = 1   // not false

scala> (if (true) 1 else 2) match { case 1 => false }
res1: Boolean = false

or

scala> throw new IllegalStateException match { case e => "ok" }
<console>:11: error: type mismatch;   // not "ok", or rather, Nothing
 found   : String("ok")
 required: Throwable
              throw new IllegalStateException match { case e => "ok" }
                                                                ^

scala> (throw new IllegalStateException) match { case e => "ok" }
java.lang.IllegalStateException
like image 62
som-snytt Avatar answered Nov 15 '22 04:11

som-snytt