Traits and Composition
Reusable Behavior
Apply a shared trait method to a value.
Reusable Behavior
ReusableBehavior.scala
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 =
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 =
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 =
val shop = new Shop()
val finalPrice = shop.discounted(price)
println("price=" + price)
println("finalPrice=" + finalPrice)
}
}
reusable-behavior
A trait method can take a parameter and compute a result. Any class that mixes in the trait reuses that behavior.