Mixin multiple traits with the same method



0

In the Example 20, you showed us a class implementing 3 traits with the same method.  To make it work, you had one trait extends another and overrides the method.

However, in the more real scenario, we typically face with the traits (or interfaces) created by different authors, and we cannot modify one to override the other.  Can you show me how a class can implement two traits having the same method and specify the specifice trait's method to use?

 

Below is the code that I am trying to make it work

 

trait iMessage1 {def writeLog {print("iMessage1.writeLog wrote this message")}

trait iMessage2 {def writeLog {print("iMessage2.writeLog wrote this message")}

trait iMessage3 {def writeLog {print("iMessage3.writeLog wrote this message")}

 

class TextFileLogger extends iMessage1 with iMessage2 with iMessage3 {

  //Here I want to say to use iMessage2.writeLog

  print("TextFileLogger is constructed")

}

object example20Main extends App {

  logger = new TextFileLogger

  logger.writeLog

}


1 Answer(s)


0

Hi Michael,

If it is a conflicting method then you need to override it to avoid the diamond problem. However, if you have your own object as a conflicting method then you can take the help of companion object as follows (Assuming a control over iMessage1 and not over iMessage2):

 

object iMessage1 {def writeLog {print("  iMessage1.writeLog wrote this message")}}

trait iMessage2 {def writeLog {print("   iMessage2.writeLog wrote this message")}}

trait iMessage3 {def writeLog {print("   iMessage3.writeLog wrote this message")}}

 

class iMessage1  {

  //iMessage1.writeLog

  print(" TextFileLogger is constructed")

}

object example20Main extends App {

  val logger = new iMessage1 with iMessage2 // This will call iMessage2 without overriding

  logger.writeLog

}

Your Answer

Click on this code-snippet-icon icon to add code snippet.

Upload Files (Maximum image file size - 1.5 MB, other file size - 10 MB, total size - not more than 50 MB)

Email
Password