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?