Search code examples
scalachainingmethod-chaining

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.


Solution

  • 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