Traits can be used as a replacement for Interfaces. We can also Define methods, as well as Create instance fields; which is not possible with Interfaces
//PS:96 //psn > a30 > a90 scala> // An example Class scala> class Subject { | def getMathMark() = { | 75 | } | } defined class Subject scala> scala> // Trait with method Declaration scala> trait Logger { | def info (msg:String):Unit | } defined trait Logger scala> scala> // Trait with method Definition scala> trait StdoutLogger extends Logger { | def info(msg:String):Unit = { | println(s"INFO: $msg") | } | } defined trait StdoutLogger scala> scala> // Mixin Class with the Trait scala> val subjectNlogger = new Subject() with StdoutLogger { | override def getMathMark() = { | info("Calling getMathMark()") | val mark = super.getMathMark() | info(s"Exitting getMathMark() : Result -> $mark") | mark | } | } subjectNlogger: Subject with StdoutLogger = $anon$1@73a31cbb scala> scala> subjectNlogger.getMathMark() INFO: Calling getMathMark() INFO: Exitting getMathMark() : Result -> 75 res12: Int = 75
No comments:
Post a Comment