Created
July 20, 2018 19:07
-
-
Save JamesMenetrey/8253cb085002f4e73f3ffd6a244fd5ec to your computer and use it in GitHub Desktop.
Scala: Type classes example with some pizzas
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 Pizza { def name: String } | |
case class CookedPizza(name: String) extends Pizza | |
case class NonCookedPizza(name: String) extends Pizza | |
def GetPizzaOfType[PizzaType <: Pizza](implicit factory: Factory[PizzaType]): PizzaType = factory.create() | |
trait Factory[PizzaType <: Pizza] { | |
def create(): PizzaType | |
} | |
object PizzaFactories { | |
implicit object CookedPizzaFactory extends Factory[CookedPizza] { | |
override def create(): CookedPizza = { | |
CookedPizza("Ma pizza cuite.") | |
} | |
} | |
implicit object NonCookedPizzaFactory extends Factory[NonCookedPizza] { | |
override def create(): NonCookedPizza = { | |
NonCookedPizza("Ma pizza non-cuite.") | |
} | |
} | |
} | |
import PizzaFactories._ | |
println(GetPizzaOfType[CookedPizza].name) | |
println(GetPizzaOfType[NonCookedPizza].name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment