How to create Instance of a case class (which extends trait with some value) in generic function

71 Views Asked by At

Let's assume I have the code:

trait Session {
  val value: Option[String] = None
}

case class A(v: Int) extends Session
case class B(v: Int, s: String) extends Session


def injectSession[T <: Session with Product](message: T)(implicit  newSession: Option[String]): T = {
 //missing code
}     

This function creates a new instance of T with the same args as message and overrides the value with newSession.

new T (same_args) {
  override val value: Option[String] = newSession 
} 

I tried to use scala-reflector, but I failed to do the overriding part, only to create a new instance with the same parameters list

implicit val session: String = "some-session"
injectSession(A(5))(session)

The reason why I used this: In the system, we have more than 300 case classes like A, B, C and we use them in unit-test as well.

I would like to inject value into the case class without changing its signature. only use 'extends' keyword

Later I will pass it via Actor system as a message

0

There are 0 best solutions below