Convert List of Ints to a SortedSet in Scala

Andy picture Andy · Jul 13, 2011 · Viewed 11.7k times · Source

If I have a List of Ints like:

val myList = List(3,2,1,9)

what is the right/preferred way to create a SortedSet from a List or Seq of Ints, where the items are sorted from least to greatest?

If you held a gun to my head I would have said:

val itsSorted = collection.SortedSet(myList)

but I get an error regarding that there is no implicit ordering defined for List[Int].

Answer

huynhjl picture huynhjl · Jul 13, 2011

Use:

collection.SortedSet(myList: _*)

The way you used it, the compiler thinks you want to create a SortedSet[List[Int]] not a SortedSet[Int]. That's why it complains about no implicit Ordering for List[Int].

Notice the repeated parameter of type A* in the signature of the method:

def apply [A] (elems: A*)(implicit ord: Ordering[A]): SortedSet[A]

To treat myList as a sequence argument of A use, the _* type annotation.