Composition and Inheritance in Scala
2 min readApr 27, 2021
Abstract class
abstract class Element {
def contents: Array[String]
}
- A method that has no implementation = The method is an abstract member of the class.
- A class with abstract members must itself be declared abstract.
- The abstract modifier signifies that the class may have abstract members that do not have an implementation.
- You cannot instantiate an abstract class.
- Terminology: declare the abstract method, define no concrete methods.
Parameterless methods
abstract class Element {
def contents: Array[String]
def height: Int = contents.length 1
def height(): Int = contents.length 2
val height = contents.length 3
}
- 1 is Parameterless Method: Recommended — if the method does not change mutable state (data field).
- 1 and 3 should be completely equivalent from a client’s point of view: uniform access principle.
- 3 faster — the field values are pre-computed; 1 takes less memory
Inheritance
class ArrayElement(conts: Array[String]) extends Element {
def contents: Array[String] = conts
}
- Private members of the superclass are not inherited in a subclass.
- Overriding. N.B. Fields and methods belong to the same namespace in Scala, so it’s ok for a field to override a parameterless method, e.g., the following is fine:
class ArrayElement(conts: Array[String]) extends Element {
val contents: Array[String] = conts
}
Parametric field
class ArrayElement(
val contents: Array[String]
) extends Element
- The field is unreassignable (i.e., val).
Override modifier
- Required when overriding a concrete member in a parent class.
- Optional when overriding an abstract member.
- Forbidden when not overriding.
Polymorphism & Dynamic Binding
- The actual method implementation invoked is determined at run time based on the class of the object, not the type of the variable or expression.
Final Modifier
- Final before class: the entire class cannot be subclassed.
- Final before member (i.e., field/method): the member cannot be overridden.
Any Class
- Superclass of all.
- AnyVal: superclass of all value classes.
- AnyRef: superclass of all reference classes.