I want to define a collection class and require its element being Ordered
Considering the code below:
class MyCollection[K: Ordered[K]] {
def func(seq: Seq[K]): Unit = {
seq.sorted
}
}
The compiler will report error No implicit Ordering defined for ord: Ordering[K]
Am I doing anything wrong? Given that we already have the constraint K: Ordered[K]
You should use:
either
OrderedwithF-bound
generalized constraint
view bound
(from stronger to weaker assumption)
or
Orderingwith context boundOrderedandOrderingare now defined so that the constraintsK => Ordered[K]andK: Orderingare actually equivalent. Indeed,Ordering.orderedtransforms one into another in one direction,Ordered.orderingToOrderedtransforms in the otherThe context bound
MyCollection[K: Ordering]is a syntax sugar forMyCollection[K](implicit ev: Ordering[K]). That's why[K: Ordered[K]]can't compile at all because of kind mismatch.Orderingis a type class butOrderedis not.Orderedis an ordinary OOP trait (you're extending it in OOP style rather than define its implicit instances in FP style). That's why although[K: Ordered]compiles but it would be incorrect semantically (implicits will not be found).Ordering and Ordered and comparing Options
Scala Ordering, Ordered, and View Bound
Get Ordering from Ordered in Scala