在scala中自定义排序

时间:2015-12-07 13:01:27

标签: scala sorting

我无法做到这一点:

abstract class AlternativeSortingType[T, B](implicit val ord: scala.math.Ordering[B]) {
  def convert(t: T): B
}

case class LengthSortingType() extends AlternativeSortingType[String, Int] {
  def convert(t: String): Int = t.length
}

class ProduceResult {
  var c: AlternativeSortingType[String, _] = LengthSortingType() 
  def sort(l: List[String]) = l.sortBy(c.convert(_))(c.ord)
}

它抱怨如下:

<console>:20: error: type mismatch;
 found   : scala.math.Ordering[_$1]
 required: scala.math.Ordering[Any]
Note: _$1 <: Any, but trait Ordering is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
             def sort(l: List[String]) = l.sortBy(c.convert(_))(c.ord)
                                                                  ^

我已经尝试将类型B放到方法中,但我没有看到如何摆脱wilcard。我希望能够通过指定任何类型的转换器进行排序。

如何使类型匹配?

1 个答案:

答案 0 :(得分:0)

我找到了一种解决方法,我甚至可以在其中制作排序组合。

abstract class AlternativeSortingType[T] extends Ordering[T] { self =>
  def &&(other: AlternativeSortingType[T]): AlternativeSortingType[T] = new AlternativeSortingType[T] {
    def compare(e: T, f: T): Int = {
      val ce = self.compare(e, f)
      if(ce == 0) other.compare(e, f) else ce
    }
  }
}

case class LengthSortingType() extends AlternativeSortingType[String] {
  def compare(e: String, f: String): Int = e.length - f.length
}

case class DictionarySortingType() extends AlternativeSortingType[String] {
  def compare(e: String, f: String): Int = if(e < f) -1 else if(e==f) 0 else 1
}

class ProduceResult {
  var c: AlternativeSortingType[String] = LengthSortingType() && DictionarySortingType()
  def sort(l: List[String]) = l.sortWith((e,f) => c.compare(e, f) < 0)
}