【问题标题】:Scala: generic function with nested case classesScala:具有嵌套案例类的通用函数
【发布时间】:2016-03-13 22:14:35
【问题描述】:

我想做一个通用函数,能够通过它们共同的“子”参数之一对不同的嵌套案例类进行排序。

目前我已经这样做了:

 sealed trait SortableByGeoPoint {
    val geographicPoint: Int
  }
  case class A(id: Int, geographicPoint: Int) extends SortableByGeoPoint
  case class B(image: String, geographicPoint: Int) extends SortableByGeoPoint

  case class C(a: A, other: String)
  case class D(b: B, other: Int)

  def sortByGeoPoint(sequence: Seq[SortableByGeoPoint]): Seq[SortableByGeoPoint] = sequence.sortBy(_.geographicPoint)

对 A 类或 B 类的序列进行排序效果很好,但我想让它适用于案例类 C 或 D(包含 SortableByGeoPoint 子类)我该如何实现呢?

我看了一下 shapeless,但没有找到方法,但任何方法(知道我稍后会添加其他类,如 C 类或 D 类)都将是完美的。

【问题讨论】:

    标签: scala generics shapeless


    【解决方案1】:

    我认为您缺少某种形式的类型约束。编译示例代码最直接的方法是:

    case class C(a: A, other: String) extends SortableByGeoPoint {
      val geographicPoint: Int = a.geographicPoint
    }
    case class D(b: B, other: Int) extends SortableByGeoPoint {
      val geographicPoint: Int = b.geographicPoint
    }
    

    这可能符合也可能不符合您的要求。所以,让我们再做一个:

    case class Z[T](b: SortableByGeoPoint, other: T)
    def sortByGeoPoint2(sequence: Seq[Z]): Seq[Z] = sequence.sortBy(_.b.geographicPoint)
    

    事实上,我可以想出许多其他方法来实现同样的结果。太多了,不胜枚举。如果您能说明一些其他要求,我可能会找到更合适的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-09
      • 2018-10-19
      • 1970-01-01
      • 2017-04-25
      • 2021-09-10
      相关资源
      最近更新 更多