Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why scala's TreeSet returns SortedSet

Tags:

scala

treeset

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)
like image 880
Elazar Leibovich Avatar asked Mar 25 '10 05:03

Elazar Leibovich


2 Answers

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.

like image 166
Kristian Domagala Avatar answered Nov 15 '22 22:11

Kristian Domagala


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.

like image 40
AaronDefazio Avatar answered Nov 15 '22 21:11

AaronDefazio