In Scala is it possible to refer to an object that is copied in a copy statement

Is there a way to refer to the object being copied in the copy statement without having to assign the object to a variable?

For example, 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")

      

+3


source to share


2 answers


Not directly. Sometimes people define a pipe method to deal with things like this (not just for classes of classes). At 2.10:

implicit class PipeEverything[A](val value: A) extends AnyVal {
  def |>[Z](f: A => Z) = f(value)
}

      

but this doesn't always save a lot of 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 block of code almost anywhere in Scala, so just creating a transient val usually doesn't matter much.

+7


source


Not an answer to your question, but aside.

You might want to look into lenses , which will allow you to do something like:



case class Foo(s: String)
sLens.mod(Foo("a"), _ + "b")

      

You can define it sLens

yourself or create an auto-generated one using the compiler plugin .

+3


source







All Articles