Search code examples
scalacollect

ListBuffer from collect func


Hi I'm wordering how could I simplify code below:

val leavesValues: ListBuffer[Double] = ListBuffer()
leavesValues.appendAll(
  leaves
    .collect { case leaf: Leaf => leaf.value.toDouble }
    .toList
)
leavesValues

I hope there is possibility to make this as oneliner.


Solution

  • Why would you want it a ListBuffer to begin with??? Mutable containers should be avoided, and in scala you almost never need them, except for some rare corner cases. I suggest, that you just pretend they don't exist at all until you get enough grasp of the language to be able to confidently distinguish those rare scenarios.

    Having said that, conversion between collection types can be done without intermediaries using a thing called breakOut. This is how you use it:

    import scala.collection.breakOut 
    val leavesValues: ListBuffer[Double] = leaves.collect { 
      case leaf: Leaf => leaf.value.toDouble
    }(breakOut)