开发者

Refactoring copy functionality

开发者 https://www.devze.com 2023-01-30 12:13 出处:网络
Is it possible to refactor the following? case class Foo( a: List[String]) { def +(s: String) = copy(a = s :: a)

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[S开发者_如何学JAVAtring],
    b: Int) {
    def +(s: String) = copy(a = s :: a)    
  }


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消