将元素添加到可变序列时出错
Error adding element to 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
^
如果您想 append to the end,请尝试以下操作:
array :+= 5
如果您想 prepend to its beginning,请执行以下操作:
array +:= 5
我猜你的假设 +
是为可变 Seq
定义的,但事实并非如此。存在到 String
的隐式转换(在 Predef
中),因此 +=
尝试用作字符串连接。
我想知道为什么这不起作用:
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
^
如果您想 append to the end,请尝试以下操作:
array :+= 5
如果您想 prepend to its beginning,请执行以下操作:
array +:= 5
我猜你的假设 +
是为可变 Seq
定义的,但事实并非如此。存在到 String
的隐式转换(在 Predef
中),因此 +=
尝试用作字符串连接。