tags:

views:

291

answers:

2

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)
+3  A: 

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.

Kristian Domagala
I I wouldn't want a `TreeSet`, I wouldn't ask for a `TreeSet` would I? Should `List(1,2,3)` give back `Iterable`? My main problem with `SortedSet` is that I can't remove an elment from it and keep its type a `SortedSet`. What you actually said here is "yes sir, it's a bag" ;-).
Elazar Leibovich
Yep, that's certainly a valid use case, and I didn't notice that a lot of those methods aren't overridden on `SortedSet`. It might be worth asking about the API design on the mailing list. In the meantime, you can either down-cast the result or build the set up using `TreeSet.empty` and `+` (as you're probably already aware).
Kristian Domagala
+1  A: 

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.