3

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?

1
  • Such things better fit companion object for me. Commented Sep 1, 2014 at 8:11

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

In this I have to duplicate any new case class paramters to copy function. Is there solution like this: def copy (parameters: _) = User(parameters, version + 1)? Currently I have to explicit add arguments to User function.
Not that I am aware of. If you only need this once I would just accept the boilerplate.
@Cherry u wod hav 2 use macros

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.