In the example we define trait MarkerTrait which will be mixed into any other classes
trait MarkerTrait { }Then we define two example classes with some methods.
ClassOne:
case class ClassOne(id: String) extends MarkerTrait{ def name: String = "ClassOne ID= " + id }and ClassTwo:
case class ClassTwo(value: String) extends MarkerTrait{ def name: String = "ClassTwo value= " + value }
After having defined classes we define the universal printer UnivPrinter object (note: is singleton) with methods print where MarkerTrait can be passed and printed out.
object UnivPrinter { private val logger = LoggerFactory.getLogger(getClass) def print(o: MarkerTrait) = { logger.debug("MarkerTrait " + o) } }As the last step we can define object MarkerTest with main method. Inside the main method we instantiate our two classes (ClassOne, ClassTwo) and pass them to the UnivPrinter.print method
object MarkerTest { private val logger = LoggerFactory.getLogger(getClass) def main(args: Array[String]): Unit = { logger.debug("Marker Trait Fundamental Pattern") UnivPrinter.print(new ClassOne("ID")) UnivPrinter.print(new ClassTwo("Value")) } }As the alternative connection to the Java world can be taken Annotation. The Annotation is not part of the Scala type system. The trait itself is much powerful in Scala then interfaces in Java as trait can define additional behaviour. This trait power can cause some implementation mixing issues.
No comments:
Post a Comment