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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With