質問

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top