Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala is it possible to reference the object being copied in the copy statement

Tags:

scala

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")
like image 360
Garrett Hall Avatar asked Dec 26 '22 10:12

Garrett Hall


1 Answers

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.

like image 133
Rex Kerr Avatar answered May 18 '23 13:05

Rex Kerr