【问题标题】:Scala: how to let the compiler infer the type from a function argument of type Seq[T]?Scala:如何让编译器从 Seq[T] 类型的函数参数推断类型?
【发布时间】:2015-12-08 22:56:34
【问题描述】:

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

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])
}

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

我想做这样的事情:

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

是否有可能做到这一点,以及如何做到这一点?

【问题讨论】:

    标签: scala type-inference


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      这里T 是该类的子类型,您可以毫无问题地访问geographicPoint 参数。

      【讨论】:

        【解决方案3】:

        糟糕,我只需要这样做:

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

        我可以调用我的函数而无需给出这样的类型:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-17
          • 2011-02-20
          • 1970-01-01
          • 2018-10-27
          • 2023-03-08
          相关资源
          最近更新 更多