Last active
December 12, 2015 12:19
-
-
Save ioRekz/4771508 to your computer and use it in GitHub Desktop.
Stackable Trait
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//every power got specific points | |
trait Power { | |
def points: Int | |
} | |
trait Speed extends Power { | |
//abstract override is the special identifier for stackable feature | |
//super is now referencing the previous trait in the linearization that is, the previous in the declaration | |
abstract override def points = super.points + 10 | |
} | |
trait Strength extends Power { | |
abstract override def points = super.points + 5 | |
} | |
//a SuperHero always have at least one power | |
class SuperHero { | |
self: Power => | |
//because even with bullshit powers u still a SuperHero | |
override def points = 1 | |
} | |
val superman = new SuperHero() with Speed with Strength | |
//because there is one and only Flash Gordon | |
object Flash extends SuperHero with Speed | |
val spoints = superman.points | |
val fpoints = Flash.points | |
println(s"Superman got $spoints points") | |
println(s"Flash got $fpoints points") | |
//prints: | |
//Superman got 16 points | |
//Flash got 11 points |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment