Is there a way to reference the object being copied in a copy statement without having to assign the object to a variable?
For instance I can do this:
case class Foo(s: String)
val f = Foo("a")
f.copy(s = f.s + "b")
But I want to do this:
case class Foo(s: String)
Foo("a").copy(s = this.s + "b")
Not directly. People sometimes define a pipe method to deal with this sort of thing (not just for case classes). In 2.10:
implicit class PipeEverything[A](val value: A) extends AnyVal {
def |>[Z](f: A => Z) = f(value)
}
but this doesn't always save that much space:
Foo("a") |> (x => x.copy(s = x.s + "b"))
{ val x = Foo("a"); x.copy(s = x.s + "b") }
Keep in mind that you can put a code block practically anywhere in Scala, so just creating a transient val is not usually a big deal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With