2

I have the following hierarchy in 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 )

I want to sort the above list based on points. How to write this in Scala?

3 Answers 3

4

You should add a method called points to your base class:

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 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))
Sign up to request clarification or add additional context in comments.

3 Comments

Kim Stebel - MyAbstractClass is provided by someone else so I can't add def points:Int to it .
If you really can't change the class, you can always insert another one into the hierarchy between MyAbstractClass and your case classes.
Thanks I was able to use your solution for another situation .
3

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. The case statement says "if x is a type that has a "point" method, then return x.points

Comments

1

Used a slightly different approach 1) Without adding points var to parent class 2) Without changing the hierarchy of classes

list containing objects of type 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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.