Friday, September 28, 2012

Pattern Matching Case Classes

  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 drink(bev: Beverage) : Unit = {
      bev match {
          case Beverage("Kaffee", 30) => println("Zucker und Milch fehlen")
          case Beverage(_, c) if c < 50 => println("Mehr Kalorien")
          case Beverage(n, c) if c < 100 => println(n + " hat zu wenig Kalorien: " + c)
          case Beverage("Cola", 400) => println("Ahhh")
          case _ => println("Bäh!")
      }
  }
  
  def eat(bev: Meal) : Unit = {
      bev match {
          case Meal(_, Food(_, a), Beverage("Coke", b)) if a >= 400 && b >= 100 => println("Haben wollen!")
          case _ => println("Bäh!")
      }
  }
  
  println(drink(Beverage("Kaffee", 30)))
  println(drink(Beverage("Tee", 10)))
  println(drink(Beverage("Cola Light", 50)))
  println(drink(Beverage("Cola", 40)))
  println(drink(Beverage("Saft", 500)))
  
  eat(Meal("Uschi's Fried Chicken", Food("Chicken", 600), Beverage("Coke Zero", 0)))
  eat(Meal("Uschi's Fried Chicken+", Food("Chicken", 600), Beverage("Coke", 100)))

No comments: