Refactoring copy functionality

2019-07-28 21:44发布

问题:

Is it possible to refactor the following?

  case class Foo(
    a: List[String]) {
    def +(s: String) = copy(a = s :: a)
  }  

  case class Bar(
    a: List[String],
    b: Int) {
    def +(s: String) = copy(a = s :: a)    
  }

回答1:

copy cannot be extracted to a super-class (if that's what you are looking for) - it's a compiler-generated method.



回答2:

You could do this with an immense amount of reflection, in a somewhat fragile way, by using the (undocumented) copy$default$1 methods, and matching types off of the copy method, and having both implement a trait that included def a: List[String] and def a_=(a0: List[String]). But it's a bad idea; the support isn't fully there (e.g. if you mixed it into a non-case-class it would fail at runtime), it's slow, and it saves only a small amount of typing.

If you have a case where it would save a huge amount of typing, I would encourage you to use code generation instead (i.e. Scala code that writes Scala code) with an extra pass for compilation.



标签: scala