10000 Update "Parenthesis () vs {}" · LannyRipple/scala.github.com@09828f8 · GitHub
[go: up one dir, main page]

Skip to content

Commit 09828f8

Browse files
committed
Update "Parenthesis () vs {}"
Provide reasoning, workaround, references.
1 parent 4e404af commit 09828f8

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

overviews/core/_posts/2014-04-08-language-pitfalls.md

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -209,13 +209,18 @@ Links to related blog posts, papers, discussions.
209209

210210
## Parenthesis `( )` vs. `{ }`
211211

212-
Description
212+
Scala's "infix notation" allows arity-1 calls to use braces instead of parenthesis which can aid readability of methods which take a function as an argument. Correctly building the function argument when using parenthesis can sometimes cause trouble.
213213

214-
**Reason:** Why does this problem exist or is this limitation in place?
214+
**Reason:** Closure syntax has some fiddly bits that are relaxed when using braces.
215215

216-
**Symptoms:** What kind of behavior or errors does this lead to?
216+
**Symptoms:** You will often see syntax errors in code that would work if using braces.
217217

218-
**Suggested solution or workaround:** General description how to fix it
218+
scala> List(1,2,3) foreach(x: Int => println(x))
219+
<console>:1: error: ')' expected but '(' found.
220+
List(1,2,3) foreach(x: Int => println(x))
221+
^
222+
223+
**Suggested solution or workaround:** When creating anonymous functions to pass to a call prefer braces. Use parenthesis for named or eta-expanded functions.
219224

220225
**Example:**
221226

@@ -225,9 +230,17 @@ Description
225230

226231
seq foreach{x: Int => println(x)}
227232

233+
Also
234+
235+
seq foreach((x: Int) => println(x))
236+
seq foreach(println)
237+
228238
**Further reading:**
229239

230-
Links to related blog posts, papers, discussions.
240+
[The Scala Language Specification: Version 2.9](http://www.scala-lang.org/docu/files/ScalaReference.pdf)
241+
* S6.12.3 Infix Operations
242+
* S6.23 Anonymous Functions
243+
* Chapter B: Change Log - Changes in Version 2.1.7 (19-Jul-2006) - Closure Syntax
231244

232245

233246
## Unchecked vs. checked pattern matching

0 commit comments

Comments
 (0)
0