Scala case class copy method is invisible from java code

I have a scala class class. I am trying to copy it with obj.copy () from java, but I do not see such a method

what i did at the moment was a workaround like:

// Hack, copy was not visible from java code. def doCopy(): MyCaseClass = { return this.copy() } 

now doCopy () is visible from java. Is there a better way to do this than this hack?

+4
source share
1 answer

There is no copy() method in the case class .

Check out all the methods generated in the case class :

 $ echo 'case class T(a1: String, a2: Int)' > test.scala $ scalac -Xprint:typer test.scala 

You will find this method:

 <synthetic> def copy(a1: String = a1, a2: Int = a2): T = new T(a1, a2); 

There Java no default parameters in Java , so you need to specify all parameters. Therefore, the copy method is useless in Java .

case class must be immutable, so you do not need copy without changing the fields.

Instead of obj2= obj.copy() you can use obj2= obj .

+5
source

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


All Articles