|
| 1 | +package com.baeldung.scala.stackabletrait |
| 2 | + |
| 3 | +object StackableTraitWithExplicitBaseAndCoreExample { |
| 4 | + trait BaseIntTransformation { |
| 5 | + def transform(value: Int): Int |
| 6 | + } |
| 7 | + |
| 8 | + trait CoreIntTransformation extends BaseIntTransformation { |
| 9 | + def transform(value: Int): Int = value |
| 10 | + } |
| 11 | + |
| 12 | + trait DoubleTransformation extends CoreIntTransformation { |
| 13 | + override def transform(value: Int): Int = |
| 14 | + super.transform(value * 2) |
| 15 | + } |
| 16 | + |
| 17 | + trait LogInt extends CoreIntTransformation { |
| 18 | + override def transform(value: Int): Int = { |
| 19 | + println(s"Transforming value: $value") |
| 20 | + super.transform(value) |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + trait CustomTransformation(f: Int => Int) extends CoreIntTransformation { |
| 25 | + override def transform(value: Int): Int = |
| 26 | + super.transform(f(value)) |
| 27 | + } |
| 28 | + |
| 29 | + @main |
| 30 | + def mainSTE(): Unit = { |
| 31 | + val logAndDouble = new CoreIntTransformation |
| 32 | + with DoubleTransformation |
| 33 | + with LogInt {} |
| 34 | + val doubleAndLog = new CoreIntTransformation |
| 35 | + with LogInt |
| 36 | + with DoubleTransformation {} |
| 37 | + val logAndCustom = new CoreIntTransformation |
| 38 | + with CustomTransformation(_ + 1) |
| 39 | + with LogInt {} |
| 40 | + |
| 41 | + println(s"Log and double: ${logAndDouble.transform(5)}") |
| 42 | + println(s"Double and log: ${doubleAndLog.transform(5)}") |
| 43 | + println(s"Log and increment: ${logAndCustom.transform(5)}") |
| 44 | + } |
| 45 | +} |
0 commit comments