Scala Collection Mismatches

Why is there a lack of consistency between collections and lists in the Scala Collection API?

For example, there is an immutable Set, but also mutable. If I want to use the latter, I can simply do this:

val set = Set[A]()
set += new A

However, there is no modified list as such. If I want to write a similar piece of code using lists, what data structure should I use? LinkedList sounds like a good candidate because it is modified, but does not have a + = method. ListBuffer seems to satisfy the requirements, but it is not a list.

After reading 2.8 Collection Documents, I came to the conclusion that the MutableList is perhaps the best fit.

I still regret somehow that was scala.collection.mutable.List.

+5
source share
5 answers

The reason for this is that Java co-opts a functional type Listto indicate that it is not (i.e., java.util.Listnot a list).

It probably does not make sense for a functional programming language to have a mutable List, since this type is an oxymoron. Therefore, ListBufferor ArrayBuffer. Or just use IndexedSeqof which there are mutable and immutable implementations

+20
source

The sequence / list analogue Setin Scala library libraries is equal Seq. Listis just a special, immutable implementation Seq, like Vector. ArrayBufferor ListBufferare typical implementations mutable.Seq.

+9

ArraySeq , , + = . java.util.ArrayList collection.JavaConversions._

, Scala List-like (, ArrayList java).

, "" "scala.immutable.List". Seq ( - ) - , , "List", / .

IndexedSeq, , . , ListBuffer .

+3

Set - - . , , mutable.Set immutable.Set.

List - , () immutable.LinearSeq. , List. , mutable.LinearSeq.

Java - .

+2

scala.collection.mutable.{LinkedList,DoubleLinkedList}. , LinearSeq. - , elem , next.

, .

val lst = collection.mutable.LinkedList(1, -2, 7, -9)
var cur = lst
while (cur != Nil) { 
  if (cur.elem < 0) cur.elem = 0
  cur = cur.next 
}

.

var cur = lst
while (cur != Nil && cur.next != Nil) { 
  cur.next = cur.next.next
  cur = cur.next 
}

I do not suggest that they be better than an immutable List. I just point out that Scala has mutable lists that look pretty similar to what you saw in your class of data structures.

0
source

All Articles