开发者

How to convert immutable Seq to mutable seq with until loop

开发者 https://www.devze.com 2023-03-04 20:52 出处:网络
I\'m trying to return a mutable Sequence with an until loop, but i have an immutable seq in return of (0 until nbGenomes) :

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 u开发者_StackOverflow中文版ntil loop to return an mutable seq ? Thanks scala community!


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)


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())
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号