Reputation: 1058
I'm learning data structure recently. There is a case that I want to design a generic trait which type should support comparable. If I need to design a generic class, I can design like the following:
class SortedType [A: Ordering](val x: A)
val x = new SortedType(3)
val y = new SortedType("Hello, World!")
However, since in scala, the trait can't have parameters with context bounds, so I can't define a trait like this trait SortedType[A: Ordering]
. How can I design the trait so that it's generic type support comparable?
Thanks for your generous advice!
Upvotes: 1
Views: 275
Reputation: 44918
The constraint [A: Ordering]
does not tell anything about the type A
itself. Instead, it specifies that an (implicitl) instance of type Ordering[A]
exists. The simplest way to guarantee the existence of an instance of type Ordering[A]
is to simply provide a method def ord: Ordering[A]
.
So, you could make the ordering into a member of the trait
, then accept an ordering as factory-method parameter:
trait SortedStuff[A] {
def ord: Ordering[A]
def x: A
}
object SortedStuff {
def apply[A: Ordering](a: A) = new SortedStuff[A] {
def ord = implicitly
def x = a
}
}
Note that this only makes sense if SortedStuff
is some kind of module that is supposed to operate on a whole bunch of A
s. Attaching an Ordering
to separate elements of A
does not make any sense - ordering is a relation between elements, not a property of each single isolated element.
Upvotes: 3