Created
March 8, 2017 14:48
-
-
Save gustavofranke/5e6b1f65bb5ad90b4c4478f4438b1b72 to your computer and use it in GitHub Desktop.
traits-basic.scala
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
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