Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document use of local variables in closures #4251

Merged
merged 2 commits into from
Sep 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions docs/script.md
Original file line number Diff line number Diff line change
Expand Up @@ -392,21 +392,31 @@ Mark = Williams
Sudha = Kumari
```

A closure has two other important features. First, it can access variables in the scope where it is defined, so that it can interact with them.

Second, a closure can be defined in an anonymous manner, meaning that it is not given a name, and is defined in the place where it needs to be used.

As an example showing both these features, see the following code fragment:
Closures can also access variables outside of their scope, and they can be used anonymously, that is without assigning them to a variable. Here is an example that demonstrates both of these things:

```groovy
myMap = ["China": 1 , "India" : 2, "USA" : 3]
myMap = ["China": 1, "India": 2, "USA": 3]

result = 0
myMap.keySet().each( { result+= myMap[it] } )
myMap.keySet().each { result += myMap[it] }

println result
```

A closure can also declare local variables that exist only for the lifetime of the closure:

```groovy
result = 0
myMap.keySet().each {
def count = myMap[it]
result += count
}
```

:::{warning}
Local variables should be declared using a qualifier such as `def` or a type name, otherwise they will be interpreted as global variables, which could lead to a race condition.
bentsherman marked this conversation as resolved.
Show resolved Hide resolved
:::

Learn more about closures in the [Groovy documentation](http://groovy-lang.org/closures.html)

(implicit-variables)=
Expand Down
Loading