Scala:如何让编译器从 Seq[T] 类型的函数参数中推断类型?

Scala: how to let the compiler infer the type from a function argument of type Seq[T]?

我正在制作一个通用函数,用于对以下 class 的不同子class进行排序:

class SortableByGeographicPoint(val geographicPoint: Int)

它的子class看起来像这样:

case class A(id: Int, override val geographicPoint: Int) extends SortableByGeographicPoint(geographicPoint)

我的函数是:

def sortByGeoPoint[T <: SortableByGeographicPoint](sequence: Seq[SortableByGeographicPoint]): Seq[T] = {
   sequence.sortBy(_.geographicPoint) map(_.asInstanceOf[T])
}

还不错,但我想使用它时必须指定类型 T,我正在寻找避免这种情况的解决方案

我想做这样的事情:

def sortByGeoPoint(sequence: Seq[T <: SortableByGeographicPoint]): Seq[T] = {
   sequence.sortBy(_.geographicPoint) map(_.asInstanceOf[T])
}

是否可以这样做,怎么做?

糟糕,我只需要这样做:

  def sortByGeoPoint2[T <: SortableByGeographicPoint](sequence: Seq[SortableByGeographicPoint]): Seq[T] = {
      sequence.sortBy(_.geographicPoint) map(_.asInstanceOf[T])
  }

而且我可以在不提供类型的情况下调用我的函数:

sortByGeoPoint2(Seq(A(1, 2)))

不需要asInstanceOf,这是不安全的:

def sortByGeoPoint3[T <: SortableByGeographicPoint](sequence: Seq[T]): Seq[T] = 
  sequence.sortBy(_.geographicPoint)

为什么不直接在 Seq 类型参数中使用 T

def sortByGeoPoint[T <: SortableByGeographicPoint](sequence: Seq[T]): Seq[T] =
  sequence.sortBy(_.geographicPoint)

此处 T 是 class 的子类型,您可以毫无问题地访问 geographicPoint 参数。