abstract class Dickmacher case class Beverage (name: String, cal: Int) extends Dickmacher case class Food (name: String, cal: Int) extends Dickmacher case class Meal (name: String, food: Food, drink: Beverage) extends Dickmacher case class Combo (starter: Dickmacher, main: Dickmacher) extends Dickmacher def unpack(food: Dickmacher) : List[Dickmacher] = food match { case a: Beverage => a :: Nil case b: Food => b :: Nil case Meal(_, b , a) => a :: b :: Nil case Combo(a, b) => unpack(a) ::: unpack(b) case _ => Nil } val coke = Beverage("Cola Light", 50) val burger = Food("Big Mac", 400) val cokeLight = Beverage("Cola", 100) val wannaBeBurger = Food("Veggie Mac", 50) val cokeCombo = Combo(coke, cokeLight) println(unpack(cokeCombo)) val burgerCombo = Combo(burger, wannaBeBurger) println(unpack(burgerCombo)) val monsterCombo = Combo(Combo(burgerCombo, cokeCombo), Food("Nachspeise", 600)); println(unpack(monsterCombo))
Friday, September 28, 2012
Pattern Matching Unpack
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment