4 - Inheritance and traits
Today we talk about Scala's trait-based inheritance system.
In many ways, it's similar to Java, but some of the concepts are slightly different.
You can find today's contents here.
Practice
Today we'll have some exercises which are mostly OO-focused and will help you apply the concepts in this course.
You are highly encouraged to read the whole exercise before you start coding.
Play around with Scala inheritance (the use of with
below has the same meaning as in Scala):
extend a class with a trait
extend a trait
extend a trait with another trait
extend a class/trait with more than one other trait
extend a trait with itself
mix-in two traits, or a class and a trait, with one method present in both
simulate a diamond problem - how do you solve it?
An Observer in Scala
We want to implement a special type of List which fires some events whenever someone adds or removes an element.
define two traits: Observable and Observer
an Observable allows Observers to register to them; add two methods, registerObserver and removeObserver to the Observable trait
an Observer must be notified whenever some event happens; add a method in the Observer which takes an Event as parameter
what is an Event (class, object, trait, superman)?
what kind of Events are there?
make a sealed trait with the necessary subclasses
create an enhanced list, call it ObservableList, which is observable
implement the necessary methods
use an existing List as a member of ObservableList, so you don't have to worry about the actual container management
create two Observers:
test your application!
(bonus) Implement a simple calculator, how you see fit
its core should be a method eval
which receives a String and returns a number as a result (Int, Double, your choice)
consider + and - first
then parentheses
then * and /
you can create a tree which resembles the structure of your operations
traverse the tree and combine nodes as you go…
… until you're left with a single node
then return the result