2016-04-13 29 views
0

我使用数组缓冲区创建可变长度数组。如何将ArrayBuffer分配给scala中的变量值

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相反分配给

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

,如果我想缓冲区分配到一个新的变量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] 

回答

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 

此外,作为侧通知,使用可变状态像这样在斯卡拉气馁。尝试使用不可变集合和val s来重写您的代码。