Closures
In Aqua, you can create an arrow within the function, enclosing its context.
1
service Hello:
2
say_hello(to_name: string, peer: string)
3
​
4
func bar(callback: string -> ()):
5
callback("Fish")
6
​
7
func foo(peer: string):
8
on peer:
9
-- Capture service resolution
10
Hello "world"
11
-- Create a closure named "closure"
12
closure = (name: string) -> string:
13
-- Use a value that's available on the definition site
14
-- To call a service that's resolved on the definition site
15
Hello.say_hello(name, peer)
16
-- Return a value from the closure; syntax is the same as in functions
17
<- name
18
-- Pass this closure to another function
19
bar(closure)
Copied!
Closures can be created anywhere in the function, starting with Aqua 0.4.1, and then used just like any other arrow (argument of arrow type, function, or service method): passed to another function as an argument, or called right there.
Closures enclose over three domains:
  • Values in scope,
  • Service resolutions,
  • Topology: place where the closure is defined should be the place where it's executed.
Comparing with functions, closures have one important difference: functions are detached from topology by default. func keyword can be used to bring this behavior to closures, if needed.
1
service Hello:
2
say_hello()
3
​
4
func foo():
5
on HOST_PEER_ID:
6
Hello "hello"
7
8
-- This closure will execute on HOST_PEER_ID
9
closure = () -> ():
10
Hello.say_hello()
11
12
fn = func () -> ():
13
Hello.say_hello()
14
15
-- Will go to HOST_PEER_ID, where Hello service is resolved, and call say_hello
16
closure()
17
18
-- Will be called on current peer, probably INIT_PEER_ID, and may fail
19
-- in case Hello service is not defined or has another ID
20
fn()
Copied!
It is not yet possible to return an arrow from an arrow.
Copy link