1

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!

1 Answer 1

3

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 As. 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.