Code Examples for

Actors in Scala

Return to chapter index

3 Scala's Language Support for Actors

  • 3.1 A scalable language
  • 3.2 Immutable and mutable state
  • 3.3 Methods and classes
  • 3.4 First-class functions
  • 3.5 Functions as control structures
  • 3.6 Pattern matching and case classes
  • 3.1 A scalable language

    3.2 Immutable and mutable state


    val fred = "Fred" val customerOrder = new CustomerOrder val count = 10
    val count: Int = 10

    3.3 Methods and classes


    def addOne(x: Int) = { x + 1 }
    def addOne(x: Int) = x + 1
    class Calculator { def addOne(x: Int) = x + 1 }
    import javax.servlet.http._ // _ means a wildcard class ScalaServlet extends HttpServlet { override def init() { super.init.() // Do something } override def doGet(req: HttpServletRequest, res: HttpServletResponse) { // No checked exceptions // Handle the get() method } }

    3.4 First-class functions


    val myList = List(1, 2, 3) val plusOne = myList.map(x => x + 1) ... List(2, 3, 4)
    val plusTwo = myList.map(_ + 2) ... List(3, 4, 5)
    // Pseudocode myMethod(someBlockOfCodeOrFunction) = { // Do something else first ... // Evaluate the parameter and return its value someBlockOfCodeOrFunction() }
    def doItByName(block: => Any) { println("Doing something first") block }
    doItByName(println("Hello, there")) ... Doing something first Hello, there

    3.5 Functions as control structures


    doItByName(println("Hello, there")) doItByName { println("Hello, there") }
    class InventoryManager { def currentInventory() = { txn { entityManager.createQuery( "select bk from Book bk" ).getResultList() } } }
    def txn[T](block: => T): T = { val entityMan = getEntityManager() // Obtain the JPA entity manager // Code is not shown EmThreadLocal.set(entityMan) // Set the entity manager in a // threadlocal variable so that the // entity manager is available to // code performed under the transaction val tx = entityMan.getTransaction() try { tx.begin() val result = block // Execute the code passed into txn tx.commit() res // Return the results, if any } finally { if (entityMan.geTransaction().isActive()) entityMan.getTransaction().rollback() if (entityMan.isOpen()) entityMan.close() EmTheadLocal.remove() } }
    def add(x: Int, y: Int) = x + y ... add(3, 5) 8 def curriedAdd(x: Int)(y: Int) = x + x ... add(3)(5) 8
    def first(x: Int) = { (y: Int) => x + y } val second = first(3) ... second(5) 8
    val socket: Socket withSocket(socket) { s => // Read from the socket, socket is available as s } // Socket is closed
    def withSocket[T](socket: Socket)(f: Socket => T): T = { try { f(socket) } finally { socket.close() } }
    def withResource[A <: {def close(): Unit}, B] (param: A) (f: A => B): B = { try { f(param) } finally { param.close() } }

    3.6 Pattern matching and case classes


    val status = message match { case ConfirmationMessage(Paid, Shipped) => Status("Order on its way") case ConfirmationMessage(Paid, Pending) => Status("Wrapping the order") case ConfirmationMessage(Paid, Returned) => Status("That's too bad!") case ConfirmationMessage(Declined, _) => Status("Wrong credit card") case _ => Status("Unknown status") }
    case class ConfirmationMessage( paymentStatus: String, shippingStatus: String )

    For more information about Actors in Scala, please visit:

    http://www.artima.com/shop/actors_in_scala

    and:

    http://booksites.artima.com/actors_in_scala

    Copyright © 2011 Artima, Inc. All rights reserved.

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.