简体   繁体   中英

scala case class copy method is unseen from java code

I have a scala case class. i'm trying to copy it with obj.copy() from java but i don't see any such method

what i did currently was a workaround as:

  // 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 it than this hack?

There is no method copy() in case class .

Let's see all methods generated in case class :

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

You'll find this method:

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

There are no default parameters in Java , so you have to specify all parameters. So method copy is useless in Java .

case class should be immutable, so you don't need to copy it without changing fields.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM