3.3 Methods and classes

Scala methods start with the def keyword, and do not require the return keyword. Instead, the value of the last expression in the method is returned. The compiler can also infer the method's return type:

  def addOne(x: Int) = { x + 1 }

Methods that consist of a single expression can alternatively leave out the surrounding braces:

  def addOne(x: Int) = x + 1

As in Java, Scala methods are part of a class:

  class Calculator {
  
  def addOne(x: Int) = x + 1

Scala inheritance works in conjunction with existing Java code, too. For instance, you can implement an HttpServlet in Scala by extending it, as shown in Listing 3.1. As the example illustrates, Scala has no checked exceptions.

    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     }    }
Listing 3.1 - Extending HttpServlet from Scala
..................Content has been hidden....................

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