Scala:如何让编译器从Seq[T]类型的函数参数推断类型?
我正在生成一个泛型函数,它对以下类的不同子类进行排序:Scala:如何让编译器从Seq[T]类型的函数参数推断类型?,scala,type-inference,Scala,Type Inference,我正在生成一个泛型函数,它对以下类的不同子类进行排序: class SortableByGeographicPoint(val geographicPoint: Int) 其子类如下所示: case class A(id: Int, override val geographicPoint: Int) extends SortableByGeographicPoint(geographicPoint) 我的职能是: def sortByGeoPoint[T <: SortableByG
class SortableByGeographicPoint(val geographicPoint: Int)
其子类如下所示:
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])
}
def sortByGeoPoint[TOops,我只需要这样做:
def sortByGeoPoint2[T <: SortableByGeographicPoint](sequence: Seq[SortableByGeographicPoint]): Seq[T] = {
sequence.sortBy(_.geographicPoint) map(_.asInstanceOf[T])
}
不需要安装asInstanceOf
,这是不安全的:
def sortByGeoPoint3[T <: SortableByGeographicPoint](sequence: Seq[T]): Seq[T] =
sequence.sortBy(_.geographicPoint)
def sortByGeoPoint3[T为什么不在Seq
类型参数中使用T
def sortByGeoPoint[T <: SortableByGeographicPoint](sequence: Seq[T]): Seq[T] =
sequence.sortBy(_.geographicPoint)
def sortByGeoPoint[T
def sortByGeoPoint3[T <: SortableByGeographicPoint](sequence: Seq[T]): Seq[T] =
sequence.sortBy(_.geographicPoint)
def sortByGeoPoint[T <: SortableByGeographicPoint](sequence: Seq[T]): Seq[T] =
sequence.sortBy(_.geographicPoint)