Elazar Leibovich
Elazar Leibovich

Reputation: 33593

Why scala's TreeSet returns SortedSet

Is there a reason that the object TreeSet.apply method returns SortedSet and not TreeSet?

The following code won't compile in scala 2.7

val t:TreeSet[Int] = TreeSet(1,2,3)

Upvotes: 7

Views: 1238

Answers (2)

AaronDefazio
AaronDefazio

Reputation: 197

This has been identified as a short coming of the current scala collection library, and is addressed in the revamped collection library that is part of scala 2.8. See http://www.scala-lang.org/sid/3# for the gory details.

Upvotes: 5

Kristian Domagala
Kristian Domagala

Reputation: 3696

The literal answer is because apply() is implemented in terms of ++, which is defined in SortedSet, and hence returns a SortedSet. ++ then goes on to use +, which is defined in TreeSet, so you can cast it back to TreeSet if it's critical (though I wouldn't recommend it, as it is implementation dependent and may change over time!).

What do you need from TreeSet that you can't get from SortedSet?

I'm not sure what the rationale behind the design decision is, though it looks like it has changed in 2.8.

Upvotes: 5

Related Questions