Traits and Composition
Mixing Traits
Combine two traits into one class.
multiple-traits
A class can mix in several traits with `extends` and `with`. It then offers the methods from every trait it combines.
Mixing Traits
MultipleTraits.scala
Replay: real traced execution (multi-file project)
trait Named {
def label: String = "item"
}
trait Counted {
def count: Int = 1
}
class Box extends Named with Counted {
override def toString: String = "[box]"
}
object Main {
def main(args: Array[String]): Unit = {
val extra = 2
val box = new Box()
val total = box.count + extra
println("label=" + box.label)
println("count=" + box.count)
println("total=" + total)
}
}
trait Named {
def label: String = "item"
}
trait Counted {
def count: Int = 1
}
class Box extends Named with Counted {
override def toString: String = "[box]"
}
object Main {
def main(args: Array[String]): Unit = {
val extra = 0
val box = new Box()
val total = box.count + extra
println("label=" + box.label)
println("count=" + box.count)
println("total=" + total)
}
}
trait Named {
def label: String = "item"
}
trait Counted {
def count: Int = 1
}
class Box extends Named with Counted {
override def toString: String = "[box]"
}
object Main {
def main(args: Array[String]): Unit = {
val extra = 5
val box = new Box()
val total = box.count + extra
println("label=" + box.label)
println("count=" + box.count)
println("total=" + total)
}
}
extra ← 2, box ← [box], total ← 3
13object Main {14 def main(args: Array[String]): Unit = {15 val extra→ 2 = 2 //@extra=0, 516 val box→ [box] = new Box()17 val total→ 3 = box[box].count + extra21819 println("label=" + box.labelitem)20 println("count=" + box.count1)21 println("total=" + total3)22 }23}outputlabel=item count=1 total=3
extra ← 0, box ← [box], total ← 1
13object Main {14 def main(args: Array[String]): Unit = {15 val extra→ 0 = 016 val box→ [box] = new Box()17 val total→ 1 = box[box].count + extra01819 println("label=" + box.labelitem)20 println("count=" + box.count1)21 println("total=" + total1)22 }23}outputlabel=item count=1 total=1
extra ← 5, box ← [box], total ← 6
13object Main {14 def main(args: Array[String]): Unit = {15 val extra→ 5 = 516 val box→ [box] = new Box()17 val total→ 6 = box[box].count + extra51819 println("label=" + box.labelitem)20 println("count=" + box.count1)21 println("total=" + total6)22 }23}outputlabel=item count=1 total=6