Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Object Oriented

Scala runs on the JVM which based on Java.
So Scala can do everything Java can.
And has all the Java object-oriented features and more

Basic concepts:

  • class and object
  • inheritance
  • abstraction (abstract class, trait)
  • polymorphism
  • data hiding

Class

A class has members:

  • field
  • method

A class is instantiated to become an object.

Fields are variables in the object scope. Methods are functions in the object scope and can implicitly
access the fields and other methods.

class Greeter:
  val name = "John"                             // field
  def sayHello() =                              // method
    s"Hello, $name"                             // access the field

val greeter = new Greeter                       // instance
greeter.name = "Lucy"                           // dot operator
val greeting = greeter.sayHello()               // call the method
println(greeting) 

Constructor

It is a good practise to make classes immutable.
This means that fields are private and written in the constructor

class Greeter (name: String = "John"):          // constructor 
  def sayHello() =
    s"Hello, $name"

val greeter = new Greeter("Lucy")               // call the constructor
val greeting = greeter.sayHello()
println(greeting)

Constructor args

class Number(x: Int)                            // private
class Number(val x: Int)                        // getter
class Number(var x: Int)                        // getter and setter    

Object

In Scala an object is a singleton class.
An object only has one instance. So every object is the same instance.

It can be used as counterpart of static methods and fields in Java.

An object has a special method apply.
Apply is called with the object name and a parameter list.
In the example below the

Greeter("Lucy") calls Greeter.apply("Lucy")

object Greeter:
  private var name: String = "John"             // private field
  def apply(name: String) =                     // apply method
    this.name = name
  def sayHello() =
    s"Hello, $name"


Greeter("Lucy")                                 // call apply method
val greeting = Greeter.sayHello()               // only one instance
println(greeting)
  

Inheritance

We can extend a class with inheritance. You could see inheritance as a copy-and-paste without copying-and-pasting

All the member from the base class are available in the inherited class.

class Meeter(name: String = "John") extends Greeter(name):   // inheritance
  def greetAndMeet() =                          // extra method
    "Meet and " + sayHello()                    // from base class

val meeter = new Meeter("Lucy")                 // call the constructor
val greeting = meeter.greetAndMeet()
println(greeting)

Information hiding

You can restrict the access to class members. Scala has the next levels of access

syntaxlevelcan access
publiceverybody
protectedprotectedneighbours and children
private[pkg]package privatein package
privateprivateonly me and companion
private[this]strict privatenot the companion object

In Scala the default is public. This you do not have to write

class AccessLevels:
  def everybody() = {}
  protected def children() = {}
  private[util] def neighbours() = {}
  private def fromCompanion() = {}
  private[this] def onlyMe() = {}

Traits

abstract class Shape(w: Int, h: Int):           // abstract class
  def area: Double                              // abstract method

class Rect(w: Int, h: Int) extends Shape(w, h):
  override def area: Double = w * h             // implement method
trait Drawable:                                 // trait
  def draw: Unit                                // abstract method

abstract class Shape(w: Int, h: Int):           // abstract class
  def area: Double                              // abstract method

class Rect(w: Int, h: Int) extends Shape(w, h) with Drawable:
  override def area: Double = w * h             // from Shape
  override def draw: Unit = println("draw")     // from Drawable