将元素添加到可变Seq时出错

时间:2017-07-30 16:53:34

标签: scala append mutable seq

我想知道,为什么这不起作用:

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

我收到一条错误消息,指出+=仅适用于字符串,为什么会这样?

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
             ^

1 个答案:

答案 0 :(得分:3)

如果您想要append to the end,请尝试以下操作:

array :+= 5

如果您想prepend to its beginning,请执行以下操作:

array +:= 5

我猜您的假设+是为可变Seq定义的,但事实并非如此。存在隐式转换(在Predef中)到String,因此+=尝试用作字符串连接。