Skip to content

Commit 10f8873

Browse files
authored
FAQ: add question about _ in lambdas (#2142)
1 parent 54315fc commit 10f8873

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

_overviews/FAQ/index.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,23 @@ has a good summary of all the meanings it has.
149149
Note that, even if the specific meaning is different,
150150
according to the situation, it usually means _"anything"_.
151151

152+
### Why doesn't my function literal with `_` in it work?
153+
154+
Not all function literals (aka lambdas) can be expressed with the `_`
155+
syntax.
156+
157+
Every occurrence of `_` introduces a new variable. So `_ + _` means
158+
`(x, y) => x + y`, not `x => x + x`. The latter function cannot be
159+
written using the `_` syntax.
160+
161+
Also, the scope of `_` is always the smallest enclosing expression.
162+
The scope is determined purely syntactically, during parsing, without
163+
regard to types. So for example, `foo(_ + 1)` always means `foo(x =>
164+
x + 1)`; it never means `x => foo(x + 1)`. The latter function cannot
165+
be written using the `_` syntax.
166+
167+
See also [SLS 6.23.2](https://scala-lang.org/files/archive/spec/2.13/06-expressions.html#placeholder-syntax-for-anonymous-functions).
168+
152169
### Can I chain or nest implicit conversions?
153170

154171
Not really, but you can [make it work](https://stackoverflow.com/a/5332804).

0 commit comments

Comments
 (0)