Home > Articles

Classes

  • Print
  • + Share This

Learn how to implement classes in Scala.

This chapter is from the book

In this chapter, you will learn how to implement classes in Scala. If you know classes in Java or C++, you won’t find this difficult, and you will enjoy the much more concise notation of Scala.

The key points of this chapter are:

  • Fields in classes automatically come with getters and setters.

  • You can replace a field with a custom getter/setter without changing the client of a class—that is the “uniform access principle.”

  • Use the @BeanProperty annotation to generate the JavaBeans getXxx/setXxx methods.

  • Every class has a primary constructor that is “interwoven” with the class definition. Its parameters turn into the fields of the class. The primary constructor executes all statements in the body of the class.

  • Auxiliary constructors are optional. They are called this.

5.1 Simple Classes and Parameterless Methods

In its simplest form, a Scala class looks very much like its equivalent in Java or C++:

class Counter {
  private var value = 0 // You must initialize the field
  def increment() { value += 1 } // Methods are public by default
  def current() = value
}

In Scala, a class is not declared as public. A Scala source file can contain multiple classes, and all of them have public visibility.

To use this class, you construct objects and invoke methods in the usual way:

val myCounter = new Counter // Or new Counter()
myCounter.increment()
println(myCounter.current)

You can call a parameterless method (such as current) with or without parentheses:

myCounter.current // OK
myCounter.current() // Also OK

Which form should you use? It is considered good style to use () for a mutator method (a method that changes the object state), and to drop the () for an accessor method (a method that does not change the object state).

That’s what we did in our example:

myCounter.increment() // Use () with mutator
println(myCounter.current) // Don't use () with accessor

You can enforce this style by declaring current without ():

class Counter {
  ...
  def current = value // No () in definition
}

Now class users must use myCounter.current, without parentheses.

  • + Share This
  • 🔖 Save To Your Account