As I write programs in Scala with case classes, I've encountered a recurring pattern where I would want to put a creator of a case class as a parameter to it for future reference. I've learnt that we can capture this pattern by putting implicit value to a case class
abstract class MessageCreator
case class SomeMessage(s:String)(implicit val creator:MessageCreator)
class MyCreator extends MessageCreator { implicit val creator = this}
class ACreator extends MyCreator { def newMessage = SomeMessage("hello") }
Then, newMessage here will have member creator
that refers to an instance of ACreator itself.
Now, I have a bunch of case classes that would do the same thing. My question is, how would you repeat this pattern without having to copy and paste (implicit val creator:MessageCreator)
every time I want to define such case class?
I have tried defining an abstract class with implicit val, then inherit them from case class, but Scala was complaining that the implicit val from abstract class was not defined in the case class. Obviously, case class cannot be inherited.
If this cannot be done programmatically, I might start looking into writing a macro (which would be a fine solution). I want to make sure that I am not missing anything here.
def apply(implicit val creator:MessageCreator) {...}
, how do I make case classes inherit such class with companion object? – In-Ho Yi