简体   繁体   English

当对象是动态的时,如何在Scala中对列表进行排序?

[英]How to sort a list in Scala when objects are of dynamic?

I have the following hierarchy in Scala 我在Scala中有以下层次结构

abstract class MyAbstractClass
case class Child1(alpha: MyAbstractClass, points: Int) extends MyAbstractClass
case class Child2(beta: Char, points: Int) extends MyAbstractClass

Now I have a list List(MyAbstractClass type objects ... either Chil1 or Child2 ) 现在我有一个列表List(MyAbstractClass类型对象...... Chil1或Child2)

I want to sort the above list based on points. 我想根据点对上面的列表进行排序。 How to write this in Scala? 如何用Scala写这个?

You should add a method called points to your base class: 您应该向基类添加一个名为points的方法:

abstract class MyAbstractClass { def points:Int }

The subclasses already implement this method, since they are case classes, so you don't need to change them. 子类已经实现了这个方法,因为它们是case类,所以你不需要更改它们。

case class Child1(alpha: MyAbstractClass, points: Int) extends MyAbstractClass
case class Child2(beta: Char, points: Int) extends MyAbstractClass

Then you can sort the list using this method. 然后,您可以使用此方法对列表进行排序。

println(List(Child2('a',0),Child1(Child2('b',2),3)).sortBy(_.points))

You can use structural typing helps you here 你可以使用结构类型帮助你

list.sortBy{
  case x: {def points: Int} => x.points
}

sortBy takes a function that when applied to each element will return the value to sort by. sortBy接受一个函数,当应用于每个元素时,它将返回值以进行排序。 The case statement says "if x is a type that has a "point" method, then return x.points case语句说“如果x是具有”point“方法的类型,则返回x.points

Used a slightly different approach 1) Without adding points var to parent class 2) Without changing the hierarchy of classes 使用略有不同的方法1)不将点var添加到父类2)而不更改类的层次结构

list containing objects of type MyAbstractClass 包含MyAbstractClass类型的对象的列表

list.sortWith((x,y) => point(x) < point(y))

def point(mylist: MyAbstractClass): Int = mylist match {
case Child1(a, p) => p
case Child2(b, p) => p
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM