0

At the moment I try to use the map function on a MutableList, because it would be more elegant then iterating with for-loops, imho.

When I do the following:

scala> ml
res2: scala.collection.mutable.MutableList[Double] = MutableList(1.0, 2.0)

So i have a MutableList like this and now I do:

scala> ml.map{ t:(Double) => t+0.2}
res3: scala.collection.mutable.LinearSeq[Double] = MutableList(1.2, 2.2)

I get a LinearSeq back. I want a MutableList back. I assume map-functions on MutableLists arent the right way to do this? Or is there a easy way to go from a LinearSeq to a MutableList?

5
  • Why do you insist on wanting a MutableList back? The result is mutable just as well. Commented Jan 10, 2013 at 10:21
  • It's a class field I assign as a MutableList, has LinearSeq access in constant-time, too? Commented Jan 10, 2013 at 10:24
  • Actually, when I run your code, I get a MutableList after the map.. which Scala version is this you're using? Commented Jan 10, 2013 at 10:26
  • Welcome to Scala version 2.8.0.final (OpenJDK Server VM, Java 1.6.0_24). Commented Jan 10, 2013 at 10:29
  • 1
    The actual version is 2.10. Just update your version... Commented Jan 10, 2013 at 11:03

2 Answers 2

1

As pagoda_5b mentioned, mutable.LinearSeq will allow the same operations as MutableList. In general, you should be instantiating the traits directly. For example, if you want a:

  • Map to store (key -> value) pairs, call Map()
  • Seq to store a list of things, call Seq()
  • Set to store a set of things, call Set()
  • Seq that has linear random access time, call IndexedSeq()
  • etc..

Also good to note is that while both MutableList and LinearSeq have constant head access time, neither of the two have constant random access time, i.e. calling linearSeq(n) will take exactly n calls to head to return.

If you want mutable versions, simply add import scala.collection.mutable and use mutable.Seq(), for example. (Technically you could import scala.collection.mutable.Seq, however it is considered good coding style to prefix all mutable collections with the package name)

Sign up to request clarification or add additional context in comments.

Comments

1

As from standard documentation:

Mutable Lists

A MutableList consists of a single linked list together with a pointer that refers to the terminal empty node of that list. This makes list append a constant time operation because it avoids having to traverse the list in search for its terminal node. MutableList is currently the standard implementation of mutable.LinearSeq in Scala.

Meaning that the returned LinearSeq is actually implemented as a MutableList => same access time

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.