scala case class copy implementation
Asked Answered
R

1

7

I can't find how copy is implemented for case class in scala.

Can I check it somehow?

I though Intellij could point me to implementation, but it doesn't want to jump and I have no idea why :/

Romish answered 25/2, 2016 at 11:29 Comment(1)
It is generated by scalac, it would look something like this https://mcmap.net/q/601836/-39-copy-39-for-non-case-classes To actually see it I think you would need to compile and decompile or enable some option in scalac.Neophyte
P
4

You can inspect the scala case class output using scalac -print ClassName.scala, as the copy is actually a compiler generated method.

Here's a given example:

case class Test(s: String, i: Int)

This is the output after filtering out noise for copy:

case class Test extends Object with Product with Serializable {
    private[this] val s: String = _;
    def s(): String = Test.this.s;

    private[this] val i: Int = _;
    def i(): Int = Test.this.i;

    def copy(s: String, i: Int): common.Test = new common.Test(s, i);
    def copy$default$1(): String = Test.this.s();
    def copy$default$2(): Int = Test.this.i();
}
Pyo answered 25/2, 2016 at 13:45 Comment(4)
This is a little weird with copy$default$1 and copy$default$2. I am still not sure what will be called when I would do Test("a",3).copy(i=5)Romish
This is what gets called: def copy(s: String, i: Int): common.Test = new common.Test(s, i);Pyo
Okay so it calls some methods of classes we don't see :-)) most acutely, does it avoid reflection?Wideman
@matanster Yes, it is compile time generated.Pyo

© 2022 - 2024 — McMap. All rights reserved.