Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Copying case classes with trait

Tags:

scala

I'm fairly new to Scala and I have a question about the best way to copy a case class while preserving data that comes from traits. For example, let's say I have the following:

trait Auditing {

  var createTime: Timestamp = new Timestamp(System.currentTimeMillis)
}

case class User(val userName: String, val email: String) extends Auditing

val user = User("Joe", "[email protected]")

Then I want to make a new copy with one parameter changed:

val user2 = user.copy(email = "[email protected]")

Now, in the example above, the property createTime does not get copied over because it is not defined in the constructor of the User case class. So my question is: assuming that moving createTime into the constructor is not an option, what is the best way for getting a copy of the User object that includes the value from the trait?

I'm using Scala 2.9.1

Thanks in advance! Joe

like image 480
Joe Avatar asked Nov 02 '12 00:11

Joe


People also ask

Can a case class extend a trait?

The answer is simple: Case Class can extend another Class, trait or Abstract Class. Create an abstract class which encapsulates the common behavior used by all the classes inheriting the abstract class.

Can traits have implementation scala?

In Scala, we are allowed to implement the method(only abstract methods) in traits. If a trait contains method implementation, then the class which extends this trait need not implement the method which already implemented in a trait.

Are Case classes immutable in scala?

It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.

Can a trait extend a class scala?

Yes they can, a trait that extends a class puts a restriction on what classes can extend that trait - namely, all classes that mix-in that trait must extend that class .


1 Answers

You can override the copy method with that behavior.

case class User(val userName: String, val email: String) extends Auditing
{
  def copy(userName = this.userName, email = this.email) {
   val copiedUser = User(userName, email)
   copiedUser.createTime = createTime
   copiedUser      
  }
}
like image 76
Reuben Doetsch Avatar answered Sep 28 '22 04:09

Reuben Doetsch