10b. Stackable Trait Pattern - RobertMakyla/scalaWiki GitHub Wiki

//Overriding Abstract Methods in Traits
//         STACKABLE TRAIT PATTERN
// similar to DECORATOR ( modificator of behaviour )


// ------------------- 1. base -------------------
trait Logger {
    def log(msg: String) // base defines abstract method
}

// ------------------- 2. stackables -------------
// decorate abstract base functionality with 'abstract override'
trait FileLogger extends Logger {
    abstract override def log(msg: String) { // must be abstract
        super.log("file " + msg) // because base log is not concrete
    }
}

trait ConsoleLogger extends Logger {
    abstract override def log(msg: String) {
        super.log("console " + msg)
    }
}

//------------------- 3. cores (traits / classes) ------
// extend base and provide core functionality
class Core extends Logger{
    def log(m: String) {
        println(m)
    } // must have concrete log method called in each trait
}

val c = new Core() with FileLogger with ConsoleLogger

c.log("hello...") // file console hello