Cherry
Cherry

Reputation: 33628

How add custom behavior to copy function in case classes in scala?

Is it possible o add custom behavior to copy function in case classes?

Something like this:

case class User (version: Integer) { //other fields are omitted
    //something like this
    override def copy (...) {
        return copy(version = version + 1, ...)
    }
}

So I do not want to rewrite copy function, just add increasing version field and copy others. How can I do that?

Upvotes: 3

Views: 1255

Answers (1)

Rüdiger Klaehn
Rüdiger Klaehn

Reputation: 12565

Adding behavior to fundamental functions such as copy is not a good idea. The functional approach is to let data be just data, and to have the behavior in the functions that operate on the data from outside.

But if you really want to do it, you will just have to re-implement the copy method, like this:

case class User(name:String, age:Int, version:Int = 0) {
  def copy(name:String = this.name, age:Int = this.age) = User(name,age,version+1)
}

Usage:

scala> User("John Doe", 25).copy(age = 26)
res4: User = User(John Doe,26,1)    

But note that you will probably have to re-implement some other methods as well for useful behavior. For example, you might not want people to be able to pass a version when constructing a user. So you need to make the constructor private and add an apply method.

You also might not want the version field to be considered for equality. So you have to redefine equals and hashCode to omit the version field. So since you have redefined almost everything that a case class gives you, you might as well make the class a normal non-case class.

In general, I think case classes should be used for pure data, while more object oriented classes that mix data and logic are best done as normal classes, even if it means a bit more typing.

Upvotes: 6

Related Questions