简体   繁体   English

在Scala中设计一个通用特征

[英]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] . 但是,因为在scala中,特征不能具有带上下文边界的参数,所以我无法定义像这个trait SortedType[A: Ordering]这样的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. 约束[A: Ordering]没有说明类型A本身的任何信息。 Instead, it specifies that an (implicitl) instance of type Ordering[A] exists. 相反,它指定存在Ordering[A]类型的(implicitl)实例。 The simplest way to guarantee the existence of an instance of type Ordering[A] is to simply provide a method def ord: Ordering[A] . 保证Ordering[A]类型实例存在的最简单方法是简单地提供一个方法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的成员,然后接受作为factory-method参数的排序:

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. 请注意,这只有在SortedStuff是某种应该在一大堆A上运行的模块时才有意义。 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. Ordering附加到A单独元素没有任何意义 - 排序是元素之间的关系,而不是每个单独的元素的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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