Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala for with () vs {} parenthesis vs curly braces [duplicate]

Tags:

for-loop

scala

I have seen for loops, comprehensions with both parenthesis () and curly braces {} they look awfully similar. I always thought they were the same, until I wrote this code:

Version 1:

def findChar(c: Char, levelVector: Vector[Vector[Char]]): Pos = {
    val positions =
      for {
        row_index <- 0 to levelVector.length - 1
        col_index <- 0 to levelVector(row_index).length - 1
        if (levelVector(row_index)(col_index) == c)
      } yield Pos(row_index, col_index)
    if (positions.length == 1) positions.head
    else throw new Exception(s"expected to find 1 match, but found ${positions.length} matches instead")
  }

Version 2:

def findChar(c: Char, levelVector: Vector[Vector[Char]]): Pos = {
    val positions =
      for (
        row_index <- 0 to levelVector.length - 1;
        col_index <- 0 to levelVector(row_index).length - 1;
        if (levelVector(row_index)(col_index) == c)
      ) yield Pos(row_index, col_index)
    if (positions.length == 1) positions.head
    else throw new Exception(s"expected to find 1 match, but found ${positions.length} matches instead")
  }

Version 1 has curly braces, while Version 2 has parenthesis. But I also noticed Version 2 didn't compile without the use of semi colons at the end of the arrow lines. Why is this?! Are these two fors even the same thing?

like image 326
user3685285 Avatar asked Mar 05 '18 07:03

user3685285


2 Answers

Nope they are not the same.

{} means to group lines of code considering the next line (\n)

() means grouping as well but doesn't consider next line (\n) so even if you have \n in the middle all of the codes inside () the lines of code are considered as one line.

like image 113
Ramesh Maharjan Avatar answered Oct 20 '22 18:10

Ramesh Maharjan


for loop definition in scala spec

Expr1 ::= ‘for’ (‘(’ Enumerators ‘)’ | ‘{’ Enumerators ‘}’) {nl} [‘yield’] Expr

Enumerators ::= Generator {semi Generator}

Generator ::= Pattern1 ‘<-’ Expr {[semi] Guard | semi Pattern1 ‘=’ Expr}

Guard ::= ‘if’ PostfixExpr

So they are the same except of newline acceptance.

For the case of curly braces in scala lexical syntax you can find:

Multiple newline tokens are accepted in the following places (note that a semicolon in place of the newline would be illegal in every one of these cases):

  • between the condition of a conditional expression or while loop and the next following expression,
  • between the enumerators of a for-comprehension and the next following expression, and
  • after the initial type keyword in a type definition or declaration.
like image 22
Evgeny Avatar answered Oct 20 '22 19:10

Evgeny