Control structures | Contents | Index |
The Reactor
trait defines control structures that simplify
programming with the non-returning react
operation. Normally,
an invocation of react
does not return. If the actor should
execute code subsequently, then one can either pass the actor's
continuation code explicitly to react
, or one can use one of
the following control structures which hide these continuations.
The most basic control structure is andThen
. It allows
registering a closure that is executed once the actor has finished
executing everything else.
actor { { react { case "hello" => // processing "hello" }: Unit } andThen { println("hi there") } }
For example, the above actor prints a greeting after it has processed
the "hello"
message. Even though the invocation of react
does not return, we can use andThen
to register the code which
prints the greeting as the actor's continuation.
Note that there is a type ascription that follows the
react
invocation (: Unit
). Basically, it let's you treat
the result of react
as having type Unit
, which is legal,
since the result of an expression can always be dropped. This is
necessary to do here, since andThen
cannot be a member of type
Nothing
which is the result type of react
. Treating the
result type of react
as Unit
allows the application of
an implicit conversion which makes the andThen
member
available.
The API provides a few more control structures:
loop { ... }
. Loops indefinitely, executing the code in
braces in each iteration. Invoking react
inside the loop body
causes the actor to react to a message as usual. Subsequently,
execution continues with the next iteration of the same loop.
loopWhile (c) { ... }
. Executes the code in braces while
the condition c
returns true
. Invoking react
in
the loop body has the same effect as in the case of loop
.
continue
. Continues with the execution of the current
continuation closure. Invoking continue
inside the body of a
loop
or loopWhile
will cause the actor to finish the
current iteration and continue with the next iteration. If the
current continuation has been registered using andThen
,
execution continues with the closure passed as the second argument
to andThen
.
The control structures can be used anywhere in the body of a
Reactor
s act
method and in the bodies of methods
(transitively) called by act
. For actors created using the
actor { ... }
shorthand the control structures can be imported
from the Actor
object.
Control structures | Contents | Index |