Reputation: 553
I'm trying to return a mutable Sequence with an until loop, but i have an immutable seq in return of (0 until nbGenomes) :
def generateRandomGenome(nbGenomes:Int): IndexedSeq[GenomeDouble]={
return ((0 until nbGenomes toSeq).map{e => generateRandomGenome})
}
Return compilation error :
found : scala.collection.immutable.IndexedSeq[org.openmole.tools.mgo.mappedgenome.genomedouble.GenomeDouble]
required: scala.collection.mutable.IndexedSeq[org.openmole.tools.mgo.mappedgenome.genomedouble.GenomeDouble]
return ((0 until nbGenomes toSeq).map{e => generateRandomGenome})
How i can force the until loop to return an mutable seq ? Thanks scala community!
Upvotes: 11
Views: 9056
Reputation: 42037
You can convert an immutable sequence to a mutable one by creating a new mutable sequence with the varargs constructor.
scala> val l = List(1,2,3)
l: List[Int] = List(1, 2, 3)
scala> scala.collection.mutable.ArraySeq(l:_*)
res0: scala.collection.mutable.ArraySeq[Int] = ArraySeq(1, 2, 3)
Upvotes: 12
Reputation: 8590
If the compiler knows which collection type to expect (and it does here as indicated by the error message) you can use scala.collection.breakOut
to allow the type to be inferred based on the expected type for the expression rather than the type of the collection itself.
def generateRandomGenomes(n: Int): collection.mutable.IndexedSeq[Double] =
(0 until n).map(_ => util.Random.nextDouble())(collection.breakOut)
(I tweaked your example a bit to stick to well-known types.)
Most (all?) collection types have some handy factory methods on their companion objects. So another way of accomplishing the same thing is to use scala.collection.mutable.IndexedSeq.fill
:
def generateRandomGenomes(n: Int): collection.mutable.IndexedSeq[Double] =
collection.mutable.IndexedSeq.fill(n)(util.Random.nextDouble())
Upvotes: 3