This file contains 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
package types | |
object SelfTypeDemo { | |
/** | |
* using the self-type we declare that any BigTimeSpender also must be a Millionaire | |
*/ | |
trait BigTimeSpender { | |
self: Millionaire => | |
def wasteMoney: Unit = println("I can waste money on champagne") | |
} | |
trait Millionaire | |
//class RichEmployee extends BigTimeSpender | |
/** | |
* This does not compile and gives following error: | |
* illegal inheritance; self-type types.SelfTypeDemo.RichEmployee | |
* does not conform to types.SelfTypeDemo.BigTimeSpender's selftype | |
* types.SelfTypeDemo.BigTimeSpender with types.SelfTypeDemo.Millionaire | |
*/ | |
//we have to mixin Millionaire | |
class RichEmployee extends BigTimeSpender with Millionaire | |
//but the order in which the traits are mixed in does not matter for this particular case | |
class OtherRichEmployee extends Millionaire with BigTimeSpender | |
def main(args: Array[String]): Unit = { | |
val employee1 = new RichEmployee | |
employee1.wasteMoney | |
val employee2 = new OtherRichEmployee | |
employee2.wasteMoney | |
//we can also create a similar type in runtime | |
val employee3 = new Object with BigTimeSpender with Millionaire | |
employee3.wasteMoney | |
} | |
} |
No comments:
Post a Comment