-
Notifications
You must be signed in to change notification settings - Fork 211
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
SCALA-601 Add example with different base and core traits
- Loading branch information
Matteo Di Pirro
committed
Jul 22, 2024
1 parent
c499c26
commit 8398deb
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
45 changes: 45 additions & 0 deletions
45
...cala/com/baeldung/scala/stackabletrait/StackableTraitWithExplicitBaseAndCoreExample.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package com.baeldung.scala.stackabletrait | ||
|
||
object StackableTraitWithExplicitBaseAndCoreExample { | ||
trait BaseIntTransformation { | ||
def transform(value: Int): Int | ||
} | ||
|
||
trait CoreIntTransformation extends BaseIntTransformation { | ||
def transform(value: Int): Int = value | ||
} | ||
|
||
trait DoubleTransformation extends CoreIntTransformation { | ||
override def transform(value: Int): Int = | ||
super.transform(value * 2) | ||
} | ||
|
||
trait LogInt extends CoreIntTransformation { | ||
override def transform(value: Int): Int = { | ||
println(s"Transforming value: $value") | ||
super.transform(value) | ||
} | ||
} | ||
|
||
trait CustomTransformation(f: Int => Int) extends CoreIntTransformation { | ||
override def transform(value: Int): Int = | ||
super.transform(f(value)) | ||
} | ||
|
||
@main | ||
def mainSTE(): Unit = { | ||
val logAndDouble = new CoreIntTransformation | ||
with DoubleTransformation | ||
with LogInt {} | ||
val doubleAndLog = new CoreIntTransformation | ||
with LogInt | ||
with DoubleTransformation {} | ||
val logAndCustom = new CoreIntTransformation | ||
with CustomTransformation(_ + 1) | ||
with LogInt {} | ||
|
||
println(s"Log and double: ${logAndDouble.transform(5)}") | ||
println(s"Double and log: ${doubleAndLog.transform(5)}") | ||
println(s"Log and increment: ${logAndCustom.transform(5)}") | ||
} | ||
} |