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.

  1. 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
      • both abstract (unimplemented)
      • one is implemented
      • both are implemented
      • fix the occurring conflicts and errors
    • simulate a diamond problem - how do you solve it?
  2. 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
      • take care to notify all the observers which are registered to you, when the time is right
    • use an existing List as a member of ObservableList, so you don't have to worry about the actual container management
    • create two Observers:
      • one that just prints out the event type and the element which was added or removed
      • one that keeps track of how many add/remove operations were applied
    • test your application!
  3. (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 /
      • pay attention to prioritization
    • you can create a tree which resembles the structure of your operations
      • create nodes for numbers and for each type of operations
      • create a for combining two nodes - you can make it an operator (something like ++) if you wish
    • traverse the tree and combine nodes as you go…
    • … until you're left with a single node
    • then return the result
sesiuni/scala/lab4.txt · Last modified: 2016/06/30 18:25 by dciocirlan