2015-12-08 84 views
2

我想做一個泛型函數能夠通過其中一個「子」參數共同排序不同的嵌套案例類。斯卡拉:泛型函數與嵌套案例類

目前我已經做到了這一點:

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子類)我該如何做到這一點?

我看了看不成形,但沒有找到一個方法來做到這一點,但沒有辦法做到這一點(知道我會添加像C級或d後其他類),將是完美的。

回答

4

我想你錯過了某種形式的類型約束。使您的示例代碼編譯最直接的方法是:

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) 

事實上,我可以想出很多其他的方法來實現這個結果。枚舉過多。如果你能說明一些其他的要求,我可能會找到一個更合適的解決方案。