case class overloading in Scala

2.9k views Asked by At

I have a legacy message in my system, and I would like to be able to map it new version the message in my system.

Why can't I overload my case class?

case class Message(a:Int, b:Int)
case class NewMessage(a:Int, b:Int, c:Int) {
  def this(msg : Message) = this(a = msg.a, b = msg.b, c = 0)
}
val msg = Message(1,2)
val converted = NewMessage(msg)

This code doesn't seem to compile. :(

2

There are 2 answers

3
Tomasz Nurkiewicz On BEST ANSWER

You must explicitly call constructor by using new operator:

val converted = new NewMessage(msg)

It works because you are actually defining a second constructor in NewMessage while ordinary:

NewMessage(1, 2, 3)

is translated to:

NewMessage.apply(1, 2, 3)
0
Knut Arne Vedaa On

You're overloading the constructor, while what you want to do is overload the apply method. You can do this on the companion object:

case class NewMessage(a: Int, b: Int, c: Int) 

object NewMessage {
  def apply(msg: Message) = new NewMessage(a = msg.a, b = msg.b, c = 0)
}

val converted = NewMessage(msg)