Scala keyword

How is "keyword priority" defined in scala?

Consider this piece of code:

for(i <- 1 to 10) yield i

This is normal, I get Seq1 to 10, but when I try to match right after:

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

Compile error: error: value head is not a member of Int.

I can surround for ... yieldin parentheses to give it priority:

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

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

Can someone explain this to me or point me to the right chapter in the spec?

+3
source share
1 answer

The second example is interpreted as:

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

An example for for syntax is as follows:

for (Enumerators) yield Expr

i match { case x => x.head } ( ), . , Expr , . :

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 _ => }

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 _ => } }

: Scala ( ). . 161 A (Scala ).

+4

Source: https://habr.com/ru/post/1793234/


All Articles