Search code examples
scalaappendmutableseq

Error adding element to mutable Seq


I'm wondering, why this doesn't work:

import scala.collection.mutable
var array: mutable.Seq[Int] = mutable.ArrayBuffer[Int]()
array += 5

I get an error stating that += works only for strings, why is this?

error: value += is not a member of scala.collection.mutable.Seq[Int]
  Expression does not convert to assignment because:
    type mismatch;
     found   : Int(5)
     required: String
    expansion: array = array.$plus(5)
       array += 5
             ^

Solution

  • In case you want to append to the end, try the following:

    array :+= 5
    

    If you want to prepend to its beginning, do the following:

    array +:= 5
    

    I guess your assumption + is defined for mutable Seqs, but it is not. An implicit conversion is present (in Predef) to Strings, so += is tried to work as String concatenation.