Implementing copy() for non-case classes/objects

Is it technically possible using compiler plugins or macros to implement a sort of copy() method on arbitrary classes and singleton objects, (not case-classes)?

Specifically, in this scenario:

trait Foo(val x: Int = 1)
trait Bar(val y: Int = 5)

object O extends Foo, Bar

val modifiedO = O.copy(x = x + 1) // y preserved **automatically** <- important requirement

Basically, I just want an auto-implemented function that, given an arbitrary object, will:

  • dynamically or reflectively read all properties of an object (not only the constructor parameters, but internal or inherited members too)
  • create a clone object with all of those same properties, but with the specified kwarg properties updated)

(please don’t recommend a way to refactor this using case classes instead. I am only interested in knowing if this current design of composing properties through multi-trait inheritance can be made possible through compiler/macro hacking)

If so, would someone point me in the right direction of reading material or examples so I can begin working on it?