scala继承例子1

import scala.collection.mutable.ArrayBuffer

object Demo3 extends App {

  abstract class Item {
    def price: Double

    def description: String
  }

  class SimpleItem(val price: Double, val description: String) extends Item

  class Bundle extends Item {
    private var items = ArrayBuffer[Item]()

    def price = items.foldLeft(0.0)(_ + _.price)

    override def description = {
      items.map(_.description).mkString(",")
    }

    def addItem(item: Item): Unit = {
      items += item
    }
  }

  val item1 = new SimpleItem(4.5, "a");
  val item2 = new SimpleItem(4.5, "b");
  val item3 = new SimpleItem(3.5, "c");

  val b = new Bundle
  b.addItem(item1)
  b.addItem(item2)
  b.addItem(item3)

  println(b.price)
  println(b.description)
}

你可能感兴趣的:(scala)