I am probably thinking about this the wrong way, but I am having trouble in Scala to use lenses on classes extending something with a constructor.
class A(c: Config) extends B(c) {
val x: String = doSomeProcessing(c, y) // y comes from B
}
I am trying to create a Lens
to mutate this class, but am having trouble doing so. Here is what I would like to be able to do:
val l = Lens(
get = (_: A).x,
set = (c: A, xx: String) => c.copy(x = xx) // doesn't work because not a case class
)
I think it all boils down to finding a good way to mutate this class.
What are my options to achieve something like that? I was thinking about this in 2 ways:
- Move the initialization logic into a companion
A
object into adef apply(c: Config)
, and change theA
class to be acase class
that gets created from the companion object. Unfortunately I can't extend fromB(c)
in myobject
because I only have access toc
in itsapply
method. - Make
x
avar
. Then in theLens.set
justA.clone
then set the value ofx
then return the cloned instance. This would probably work but seems pretty ugly, not to mention changing this to avar
might raise a few eyebrows. - Use some reflection magic to do the copy. Not really a fan of this approach if I can avoid it.
What do you think? Am I thinking about this really the wrong way, or is there an easy solution to this problem?