Skip to content

Instantly share code, notes, and snippets.

@gustavofranke
Created March 8, 2017 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gustavofranke/5e6b1f65bb5ad90b4c4478f4438b1b72 to your computer and use it in GitHub Desktop.
Save gustavofranke/5e6b1f65bb5ad90b4c4478f4438b1b72 to your computer and use it in GitHub Desktop.
traits-basic.scala
trait Bird {
val name: String
}
trait Flying {
def flyMessage: String
def fly() = println(flyMessage)
}
trait Swimming {
def swim() = println("I'm swimming")
}
class Pigeon extends Bird with Flying {
override val flyMessage = "I'm a good flyer"
override val name = "Pigeon"
}
class Pigeon5 extends Bird with Swimming {
val flyMessage = "I'm a awesome flyer"
override val name = "Pigeon55"
}
val pigeon = new Pigeon with Swimming
pigeon.swim() // I'm swimming
pigeon.fly() // I'm a good flyer
pigeon.name // Pigeon
val pigeon5 = new Pigeon5 with Flying
pigeon5.swim() // I'm swimming
pigeon5.fly() // I'm a awesome flyer
pigeon5.name // Pigeon55
case class Human(name: String)
val asd = Human("Gustavo")
asd.name
sealed trait Skill
case class Swimmer(name: String) extends Skill with Swimming
case class SuperHuman(name: String) extends Skill with Flying {
override def flyMessage: String = "I'm not a plane"
}
val dfg = Swimmer("swimmer")
dfg.swim() //I'm swimming
val qwe = SuperHuman("Asdf")
qwe.fly() //I'm not a plane
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment