Created
November 9, 2011 13:12
-
-
Save seratch/1351382 to your computer and use it in GitHub Desktop.
traits.scala #daimonscala 21
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
| type HasName = { def name: String } | |
| trait CanSpeak { this: HasName => | |
| def introduce = println("Hi, I'm " + name + ".") | |
| } | |
| trait CanRun { this: HasName => | |
| def run = println(name + " start running!") | |
| } | |
| trait CanEat { this: HasName => | |
| def eat = println(name + " start eating!") | |
| } | |
| case class Person(name : String) | |
| val andy = new Person("Andy") with CanSpeak with CanRun with CanEat | |
| andy.introduce | |
| andy.run | |
| andy.eat | |
| trait YetAnotherRun { | |
| def run = println("Run!" * 3) | |
| } | |
| val forrest = new Person("Forrest") with YetAnotherRun | |
| forrest.run | |
| /* | |
| scala> val forrest = new Person("Forrest") with CanRun with YetAnotherRun | |
| <console>:12: error: overriding method run in trait CanRun of type => Unit; | |
| method run in trait YetAnotherRun of type => Unit needs `override' modifier | |
| val forrest = new Person("Forrest") with CanRun with YetAnotherRun | |
| ^ | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment