Created
May 21, 2015 08:19
-
-
Save yutaono/f082a70c0ac5ddb3bedb to your computer and use it in GitHub Desktop.
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
sealed trait Animal | |
case class Dog(name: String) extends Animal | |
case class Cat(name: String) extends Animal | |
val dogs = List(Dog("pochi"), Dog("gon")) | |
val cats = List(Cat("tama"), Cat("kuro")) | |
val animals: List[Animal] = List(dogs, cats).flatten | |
trait AnimalLogic[A <: Animal] { | |
def getName(animal: A): String | |
} | |
implicit object DogLogic extends AnimalLogic[Dog] { | |
override def getName(dog: Dog): String = dog.name | |
} | |
implicit object CatLogic extends AnimalLogic[Cat] { | |
override def getName(cat: Cat): String = cat.name | |
} | |
def getName[A <: Animal](animal: A)(implicit logic: AnimalLogic[A]): String = { | |
logic.getName(animal) | |
} | |
val names = animals.map { | |
case dog: Dog => getName(dog) | |
case cat: Cat => getName(cat) | |
} | |
println(names) // List(pochi, gon, tama, kuro) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ではできないみたい