Question

I have an ArrayBuffer from which I want to convert all objects to their respective size to an existing buffer:

trait Obj {
  def size: Int
}

def copySizes(input: ArrayBuffer[Obj], output: ArrayBuffer[Int]): Unit = {
  output.clear()
  input foreach { obj =>
    output += obj.size
  }
}

Is there a better idiomatic way to describe copySizes in scala ? I was thinking about a syntax like:

input.mapTo(_.size, output)
Was it helpful?

Solution

You could

output ++= input.view.map(_.size)

which has a non-negligible additional overhead (~2x runtime) but is more compact. You can write your version more compactly, though:

input.foreach{ output += _.size }

so I don't see much reason not to use it.

OTHER TIPS

Have you considered trying to foldLeft on the input buffer using the output buffer as the accumulator and doing the append in the function body?

val output = input.foldLeft(ArrayBuffer[Int]())(_ += _.size)

As @Rex Kerr mentioned, there might be a performance hit here vs the foreach that you were doing, but I wasn't sure that this was a high performance need piece of code. I guess it depends on how many items are in the buffer and how often this code is hit. If it's a low number of items or this is not a piece of code that is consistently hit, then you might be better with something that is more functional (the fold) vs something that is more side effect based (the foreach).

There generally comes a time when writing Scala code where you have to make that decision; do I care about functional purity/pretty scala code or is this something that needs to be optimized. I try to stay on the purely functional side when possible and then performance test my system and find hotspots and optimize when needed. Premature optimization is the root of all evil (or something like that) =)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top