Case class copy() method abstraction

前端 未结 5 825
孤独总比滥情好
孤独总比滥情好 2021-01-02 02:08

I would like to know if it is possible to abstract the copy method of case classes. Basically I have something like sealed trait Op and then something like

5条回答
  •  走了就别回头了
    2021-01-02 02:42

    As Mirko correctly pointed out, you cannot really abstract over copy method. I support Daniel's view, that cloning may be what you want, although I would wrap it with some helper code to reduce boilerplate.

    You can define a mixin trait with copy functionality and just mix it into your case classes then:

    trait ClonableAs[T] extends Cloneable { this: T => 
      def makeClone() = super.clone().asInstanceOf[T]
    }
    
    case class Foo(i: Int) extends ClonableAs[Foo]
    
    List(Foo(1), Foo(2), Foo(3)).map(_.makeClone())
    

    That way instead of adding an identical method to each of your case classes, you make them extend the helper trait, which makes them cleaner and saves you some keystrokes.

    On the other hand, the cloning would make no sense for immutable objects, so I infer your classes have mutable state. I would advise you to reconsider if you really cannot make them immutable, and use that type of cloning only at last resort. Immutability will protect yourself from a class of errors.

提交回复
热议问题