Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between curly bracket and parenthesis in a Scala for loop?

Tags:

scala

This is my first day of studying Scala (using the "Beginning Scala" book). When I read the for loops in Scala, there are 2 examples:

val books = List("Beginning Scala", "Beginning Groovy", "Beginning Java", "Scala in easy steps", "Scala in 24 hours")

[1]

for (book<-books if book.contains("Scala")) println(book)

[2]

for { book <- books
  bookVal = book.toUpperCase()
}
println(bookVal)

The thing that confused me is:

In [1] for uses parentheses "()" to wrap the loop control block while in [2] it uses curly braces "{}". I wonder if this is just different syntax but the same purpose or if they actually mean something different?

Thanks

like image 542
Kuan Avatar asked Aug 10 '15 18:08

Kuan


People also ask

What is the difference between curly braces and parentheses?

Parentheses are for separating citations or other asides from the body text. Brackets show changes within quoted material. Braces —sometimes known as curly brackets—are not typically used except in technical and mathematical writing.

What is {} used for in code?

Brackets, or braces, are a syntactic construct in many programming languages. They take the forms of "[]", "()", "{}" or "<>." They are typically used to denote programming language constructs such as blocks, function calls or array subscripts. Brackets are also known as braces.

What are {} brackets called?

Curly brackets {} Curly brackets, also known as braces or curly braces, are rarely used in formal writing and are more common in other fields such as science, math, and computing. Some style guides will allow them to be used for one specific purpose: grouping together a set.

Why we use curly parenthesis not any other brackets?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.


1 Answers

Curly braces are usually used if you have multiline expression or expression which contains few other experession. If you're able (or want) to write in single line using semicolons you may use parentheses. Every for loop you can write with curly braces but using of parentheses is reduced.

If some other case curly braces allow you to use easier syntax to write partial function or pattern matching.

If you write in REPL following code:

for (
    i <- List(1,2,3)
    y = i * i
) yield y

it wouldn't compile e.g.

like image 98
Sergii Lagutin Avatar answered Nov 15 '22 01:11

Sergii Lagutin