barclar
barclar

Reputation: 533

Is it possible to reference the chained object in a method call chain?

I have a builder call chain in which one of the calls must append to the default value, e.g.

var x = new X()
  .setA(1)
  .setB(2)
x = x.setList(x.getList :+ "itemtoappend")

Is there any way to inline the setList call? (X is a 3rd party library)

I'm hoping there is be a keyword, say "chain", used like this:

val x = new X()
  .setA(1)
  .setB(2)
  .setList(chain.getList :+ "itemtoappend")

Assuming I don't have the ability to write an appendToList method on X, and don't want to write and implicitly convert to/from a class MyX that has appendToList.

Upvotes: 2

Views: 324

Answers (2)

jwvh
jwvh

Reputation: 51271

It looks like you want to access the object twice at the same time you're building it.

class X {
  def setA(a: Int): X = this
  def setB(b: Int): X = this
  def setList(ss: Seq[String]): X = this
  def getList = Seq("head")
}

val x: X = Option( new X().setA(1).setB(2)
                 ).map(z => z.setList(z.getList :+ "itemtoappend")).get

Upvotes: 1

Bergi
Bergi

Reputation: 664356

I think the standard approach is write a method that does both setting and getting, being passed a function. You'd call it as

val x = new X()
  .setA(1)
  .setB(2)
  .list(_ :+ "itemtoappend")

Upvotes: 0

Related Questions