I am a beginner to Scala. I want to Sort a Set and then provide user with new sorted Set so old Set should remain the same.
I have already a trait like example BaseTrait[+A] and I want to enrich it.
trait BaseSet[+A] { //it extends scala Set
def +[B >: A](item: B): BaseSet[B]
def -[B >: A](item: B): BaseSet[B]
def size: Int
def contains[B >: A](item: B): Boolean
}
trait SetWithSort[+A] extends BaseSet[A] {
abstract def sort[B](implicit ordering: Ordering[_ >: B]): Set[B]
def logicBeforeSorting(): Set[B] ={
sort
}
}
object MainObject {
def OrderByName:Ordering[String] => Set[String] = ???
def execute[T](callback:Ordering[T]): Ordering[T] = callback //Problem, I // want Set[T] here
// I want to get a new Set with elements sorted as per my provided ordering
}
You can use SortedSet as mentioned in the comments, example:
import scala.collection.SortedSet
def sortSet[A](unsortedSet: Set[A])(implicit ordering: Ordering[A]): SortedSet[A] =
SortedSet.empty[A] ++ unsortedSet
If you provide an implicit argument of type Ordering[A], this ordering will be used.
Usage with default ordering:
sortSet(Set(2, -1, 0, -2, 1)) // result TreeSet(-2, -1, 0, 1, 2)
the above works because Scala already provides an implicit Ordering[Int] in scope
Usage with provided ordering:
implicit val reverseOrdering = Ordering[Int].reverse
sortSet(Set(-15, 100, -3, 101, -5)) // result TreeSet(101, 100, -3, -5, -15)
// or by providing ordering directly:
val reverseOrdering = Ordering[Int].reverse
sortSet(Set(-15, 100, -3, 101, -5))(reverseOrdering) // result TreeSet(101, 100, -3, -5, -15)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With