简体   繁体   中英

Design a generic trait in Scala

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM