Skip to content

Instantly share code, notes, and snippets.

@seratch
Created November 9, 2011 13:12
Show Gist options
  • Save seratch/1351382 to your computer and use it in GitHub Desktop.
Save seratch/1351382 to your computer and use it in GitHub Desktop.
traits.scala #daimonscala 21
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