Apply a shared trait method to a value.

reusable-behavior A trait method can take a parameter and compute a result. Any class that mixes in the trait reuses that behavior.

Reusable Behavior

price
ReusableBehavior.scala
Replay: real traced execution (multi-file project)
trait Discount {
  def discounted(price: Int): Int = price - 2
}

class Shop extends Discount {
  override def toString: String = "[shop]"
}

object Main {
  def main(args: Array[String]): Unit = {
    val price = 10
    val shop = new Shop()
    val finalPrice = shop.discounted(price)

    println("price=" + price)
    println("finalPrice=" + finalPrice)
  }
}
trait Discount {
  def discounted(price: Int): Int = price - 2
}

class Shop extends Discount {
  override def toString: String = "[shop]"
}

object Main {
  def main(args: Array[String]): Unit = {
    val price = 5
    val shop = new Shop()
    val finalPrice = shop.discounted(price)

    println("price=" + price)
    println("finalPrice=" + finalPrice)
  }
}
trait Discount {
  def discounted(price: Int): Int = price - 2
}

class Shop extends Discount {
  override def toString: String = "[shop]"
}

object Main {
  def main(args: Array[String]): Unit = {
    val price = 30
    val shop = new Shop()
    val finalPrice = shop.discounted(price)

    println("price=" + price)
    println("finalPrice=" + finalPrice)
  }
}
  1. price ← 10, shop ← [shop], finalPrice ← 8

    9object Main {10  def main(args: Array[String]): Unit = {11    val price→ 10 = 10 //@price=5, 3012    val shop→ [shop] = new Shop()13    val finalPrice→ 8 = shop[shop].discounted(price10)1415    println("price=" + price10)16    println("finalPrice=" + finalPrice8)17  }18}
    outputprice=10
    finalPrice=8
  1. price ← 5, shop ← [shop], finalPrice ← 3

    9object Main {10  def main(args: Array[String]): Unit = {11    val price→ 5 = 512    val shop→ [shop] = new Shop()13    val finalPrice→ 3 = shop[shop].discounted(price5)1415    println("price=" + price5)16    println("finalPrice=" + finalPrice3)17  }18}
    outputprice=5
    finalPrice=3
  1. price ← 30, shop ← [shop], finalPrice ← 28

    9object Main {10  def main(args: Array[String]): Unit = {11    val price→ 30 = 3012    val shop→ [shop] = new Shop()13    val finalPrice→ 28 = shop[shop].discounted(price30)1415    println("price=" + price30)16    println("finalPrice=" + finalPrice28)17  }18}
    outputprice=30
    finalPrice=28