1

I have a library class which I can't change:

class MultiPart {
  private val _parts: Seq[Part] = Seq.empty[Part])

  def addHead(head: Head): MultiPart = Multipart(_parts :+ head)

  def addPart(part: Part): MultiPart = Multipart(_parts :+ part)
}

In my code, I want to construct an immutable object of class Multipart, while iterating in a for loop. But I am not able to figure out how to do that. My current code looks like :

var mp: MultiPart = new MultiPart().addHead(head)
arrParts.foreach(x => mp.addPart(x))

Is there a way to fix this?

2
  • 4
    It seems you want a foldLeft/foldRight. Commented Apr 1, 2016 at 16:22
  • If you want it immutable, why don't you just create a new MultiPart with new Seq[Part]? Commented Apr 1, 2016 at 18:58

1 Answer 1

1

Looks like you should use foldLeft or foldRight (similar functions in other languages are usually called reduce)

arrParts.foldLeft(new MultiPart().addHead(head))(
    (list, part) => {
        list.addPart(part)
    }
)

There's some good examples on this page if you're confused: http://oldfashionedsoftware.com/2009/07/30/lots-and-lots-of-foldleft-examples/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.