Search code examples
scalafor-comprehension

For-comprehension for two arrays of the same length


I have two Seq[Array[Byte]] arrays:

var o1: Seq[Array[Byte]]
var o2: Seq[Array[Byte]]
//...

I need to mutate the o1 Seq of Arrays so that each array of o1 is replaced with Array of o2 of the same position iff the array of o2 has non-zero length.

Is it possible to do with for-comprehension?


Solution

  • This seems like a better job for zip

    o1 zip o2 map { case (l, r) => if(r.nonEmpty) r else l }
    

    If you don't like creating the intermediate seq with o1 zip o2, you could lazily build up the combination using iterators:

    (o1.iterator zip o2.iterator map { case (l, r) => if(r.nonEmpty) r else l }).toList
    

    If you really want to mutate, first make sure to use a collection.mutable.IndexedSeq since its mutation method (update) takes an index. If you try to mutate a general Seq, you might get O(n) updates due to linked list-ish structures.

    for {
      (replacement, index) <- o2.iterator.zipWithIndex
      if replacement.nonEmpty
    } o1(index) = replacement
    

    This is actually just syntax sugar for something like:

    o2.iterator.zipWithIndex.foreach {
      case (replacement, index) =>
        if(replacement.nonEmpty) o1.update(index, replacement)
    }