3

I have a Vector of objects of a particular class. How can I sort them? Which comparison method must I add to a class to make it sortable? If not method, which ordering function should I implement?

1

1 Answer 1

4

Method sorted of Vector takes an implicit parameter of type math.Ordering[B], which it uses for sorting. There are several ways to provide it:

  1. Define an implicit math.Ordering[MyClass]. You can create an Ordering for your class using the methods from the Ordering companion object:

    case class MyClass(field: Int)
    object MyClass {
      implicit val MyClassOrdering: Ordering[MyClass] = Ordering.by(_.field)
    }
    

    If the Ordering is defined in the companion object of MyClass, it'll be provided for sorting automatically. Otherwise, you'll have to import it manually before calling sorted. Ordering allows to provide several different ordering defined on a class, and to import or provide explicitly the one you want.

  2. Have your class extend Ordered[MyClass] by overriding compare method. In this case the necessary Ordering will be created implicitly.

    case class MyClass(field: Int) extends Ordered[MyClass] {
      def compare(other: MyClass): Int = this.field compareTo other.field
    }
    

    This will also add methods <, >, <=, >= to the class.

  3. Use sortBy or sortWith methods of Vector, which take a function and don't need an Ordering parameter.

    vectorOfMyClass.sortBy(_.field)
    vectorOfMyClass.sortWith(_.field < _.field)
    
Sign up to request clarification or add additional context in comments.

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.