0

Let's say I've got a case class definition:

// Scala 2.13
case class Employee(name: String, id: Int) 

Then I'd like to specify an inline implicit ordering like:

es.sorted(implicit ord: Ordering[Employee] = Ordering.by(_.name))

which doesn't work.

What could be a correct way to do that?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Sergey Bushmanov
  • 23,310
  • 7
  • 53
  • 72

1 Answers1

2

Try to specify Ordering explicitly at a call site

case class Employee(name: String, id: Int)

es.sorted[Employee](Ordering.by(_.name))
// es.sorted(Ordering.by((_: Employee).name))
// es.sortBy(_.name)

or define default Ordering at the definition site (an instance of the type class Ordering for the data type Employee)

case class Employee(name: String, id: Int)
object Employee {
  implicit val employeeOrdering: Ordering[Employee] = Ordering.by(_.name)
}

es.sorted
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • Just wondering: why implicit ordering needs to be specified in the companion object and specifying in the class definition doesn't work? – Sergey Bushmanov Feb 23 '23 at 14:03
  • 1
    @SergeyBushmanov See https://stackoverflow.com/questions/5598085/where-does-scala-look-for-implicits What you're defining in a class depends on an instance of the class (`this`). Implicit `Ordering[Employee]` is defined for the whole `class Employee`, not for its specific `this` (should be `static` in Java terminology). Another question is not why is defined but why is found. Well, that's convention. See details in the question linked. – Dmytro Mitin Feb 23 '23 at 14:07