11.2 Control structures

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, you can either pass the actor's continuation code explicitly to react, or use one of the control structures, described in this section, which hide these continuations.

The most basic control structure is andThen. It allows you to register a closure that is executed once the actor has finished executing everything else.

    actor {
      {
        react {
          case "hello" => // processing "hello"
        }: Unit
      } andThen {
        println("hi there")
      }
    }
Listing 11.1 - Using andThen for sequencing.

For example, the actor shown in Listing 11.1 prints a greeting after it has processed the "hello" message. Even though the invocation of react does not return, you can use andThen to register the code that prints the greeting as the actor's continuation.

Note that there is a type ascription, ": Unit," that follows the react invocation. This essentially allows you to treat the result of react as having type Unit, which is legal since the result of any expression can always be converted to Unit. This is necessary since andThen cannot be a member of type Nothing, which is the result type of react. Treating the result type of react as Unit enables the application of an implicit conversion that makes the andThen member available.

The API provides a few more control structures:

  • loop { ...} Loops indefinitely, executing the code in braces 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 will continue with the closure passed as the second argument to andThen.

You can use the control structures 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset