简体   繁体   中英

scala keyword precedence

how is "keyword precedence" defined in scala?

Consider this piece of code:

for(i <- 1 to 10) yield i

This is OK, I get a Seq from 1 to 10, but when i try to match right after:

for(i <- 1 to 10) yield i match {case x => x.head}

There is a compile error: error: value head is not a member of Int .

I can surround for ... yield in parentheses to give it precedence:

{for(i <- 1 to 10) yield i} match {case x => x.head}

But I'm still wondering how is the second example code interpreted. I would expect the second example to work properly as well, without surrounding it with parens.

Can anyone explain it to me or point me to the right chapter in specification?

The second example is interpreted as:

for(i <- 1 to 10) yield { i match {case x => x.head} } // won't compile

The approximate syntax for for is like:

for (Enumerators) yield Expr

Since i match { case x => x.head } parses as a valid expression (token wise), that's how the compiler will see it. So if Expr looks like an expression, that's how it will be treated. By that reasoning, the following statements are valid:

for(i <- 1 to 10) yield for(j <- 1 to 2) yield (i, j)
for(i <- 1 to 10) yield if (i % 2 == 0) 'a' else 'b'
for(i <- 1 to 10) yield try { 1 / (i - 5) } catch { case _ => }

and they are all equivalent to

for(i <- 1 to 10) yield { for(j <- 1 to 2) yield (i, j) }
for(i <- 1 to 10) yield { if (i % 2 == 0) 'a' else 'b' }
for(i <- 1 to 10) yield { try { 1 / (i - 5) } catch { case _ => } }

Note: the Scala Language Specification is available here (first link). The relevant section is on page 161 in the Chapter A (Scala Syntax Summary).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM