【问题标题】:Error adding element to mutable Seq将元素添加到可变 Seq 时出错
【发布时间】:2017-07-31 01:03:20
【问题描述】:

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

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
             ^

【问题讨论】:

  • 同时使用 var 和可变集合是冲突的。最好将可变集合声明为val
  • @cchantep 如果我这样做,我将无法改变集合..."Expression does not convert to assignment because receiver is not assignable"
  • 看看doc。无论如何,将var 与可变类型一起使用是没有意义的

标签: scala append mutable seq


【解决方案1】:

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

array :+= 5

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

array +:= 5

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

【讨论】:

  • 对。如果您想添加/追加,请使用Buffer,而不是mutable.Seq
猜你喜欢
  • 2012-01-07
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多