【问题标题】:How to assign the ArrayBuffer to a varaible in scala如何将ArrayBuffer分配给scala中的变量
【发布时间】:2016-04-13 00:28:25
【问题描述】:

我正在使用数组缓冲区创建可变长度数组。

import scala.collection.mutable.ArrayBuffer

val b = ArrayBuffer[Int]() // empty array!
b += (1, 2, 3, 5) // append and output: ArrayBuffer(1, 2, 3, 5)

现在我想将变量 b 分配给 a

var a = Array[Int]() // a(0) = 10 // error because a is empty array
a = b.toArray // Array(1, 1, 2)

反之,如果我想将Buffer分配给一个新的变量c,就会出错。

var c = ArrayBuffer[Int]()
c = a.toBuffer // Conversely, convert the array a to an array buffer.
<console>:8: error: missing arguments for method apply in class GenericCompanion; follow this method with `_' if you want to treat it as a partially applied function
var c = ArrayBuffer[Int]

【问题讨论】:

    标签: arrays scala arraybuffer


    【解决方案1】:

    c 的类型被推断为ArrayBuffer,而a.toBuffer 返回mutable.Buffer(它是ArrayBuffer 的超类之一)。因此,简单的解决方法是将c 的类型显式设置为mutable.Buffer[Int]

    import scala.collection.mutable
    import scala.collection.mutable.ArrayBuffer
    
    var a = Array[Int]()
    var c:mutable.Buffer[Int] = ArrayBuffer[Int]()
    c = a.toBuffer
    

    另外,作为一个附带说明,在 Scala 中不鼓励使用像这样的可变状态。尝试使用不可变集合和vals 重写您的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      相关资源
      最近更新 更多