0

I am trying to leverage Ordering[T] in scala to compare objects but does not work with 2.11 version of scala but works in 2.12 scala version.

Need to understand the binding mechanism to get resolved in 2.11 vs 2.12 scala versions.

    case class Team(city:String, mascot:String)

    //Create two choices to sort by, city and mascot
     object MyPredef3 {
  implicit val teamsSortedByCity: Ordering[Team] =
    (x: Team, y: Team) => x.city compare y.city
  implicit val teamsSortedByMascot: Ordering[Team] =
    (x: Team, y: Team) => x.mascot compare y.mascot
}

object _6OrderingAList extends App {
  //Create some sports teams
  val teams = List(Team("Cincinnati", "Bengals"),
    Team("Madrid", "Real Madrid"),
    Team("Las Vegas", "Golden Knights"),
    Team("Houston", "Astros"),
    Team("Cleveland", "Cavaliers"),
    Team("Arizona", "Diamondbacks"))

  //import the implicit rule we want, in this case city
  import MyPredef3.teamsSortedByCity

  //min finds the minimum, since we are sorting
  //by city, Arizona wins.
  println(teams.min.city)
}
Sampat Kumar
  • 492
  • 1
  • 6
  • 14

1 Answers1

2

You are using the Single Abstract Method Types language feature. This feature is only available in Scala 2.12+, and in scala 2.11.x must be enabled by -Xexperimental compiler flag. See this: Scala single method interface implementation

Update: adding implementation of Ordering without SAM. Thanks for the suggestion!

implicit val teamsSortedByCity: Ordering[Team] = new Ordering[Team] {
  override def compare(x: Team, y: Team) = x.city compare y.city
}
memoryz
  • 479
  • 2
  • 10
  • 2
    I think it would be also good to show how to create the instance of `Ordering` without using the **SAM**, since that is probably a better idea than enable `-Xexperimental` – Luis Miguel Mejía Suárez Apr 29 '21 at 19:54