Class class overload in Scala

I have an outdated message on my system, and I would like to be able to display a new version of the message on my system.

Why can't I overload the 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 does not seem to compile. :(

+4
source share
2 answers

You must explicitly call the constructor using the new operator:

 val converted = new NewMessage(msg) 

This works because you are actually defining a second constructor in NewMessage , and the usual one:

 NewMessage(1, 2, 3) 

translates to:

 NewMessage.apply(1, 2, 3) 
+5
source

You are overloading the constructor, and what you want to do is overload the apply method. You can do this on a 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) 
+11
source

Source: https://habr.com/ru/post/1416055/


All Articles