【问题标题】:Scala Ordering Using Scala 2.11 having issue , but no issue while using 2.12Scala Ordering Using Scala 2.11 有问题,但使用 2.12 时没有问题
【发布时间】:2021-04-29 17:31:57
【问题描述】:

我正在尝试利用 scala 中的 Ordering[T] 来比较对象,但不适用于 2.11 版本的 scala,但适用于 2.12 版本。

需要了解在 2.11 与 2.12 scala 版本中解决的绑定机制。

    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)
}

【问题讨论】:

  • 问题是什么?

标签: scala comparator


【解决方案1】:

您正在使用单一抽象方法类型语言功能。此功能仅在 Scala 2.12+ 中可用,并且在 Scala 2.11.x 中必须通过 -Xexperimental 编译器标志启用。 看到这个:Scala single method interface implementation

更新:添加不带 SAMOrdering 实现。感谢您的建议!

implicit val teamsSortedByCity: Ordering[Team] = new Ordering[Team] {
  override def compare(x: Team, y: Team) = x.city compare y.city
}

【讨论】:

  • 我认为展示如何在不使用 SAM 的情况下创建 Ordering 的实例也很好,因为这可能比启用 -Xexperimental 更好
猜你喜欢
  • 2021-10-22
  • 1970-01-01
  • 2017-05-13
  • 2020-08-25
  • 2019-04-22
  • 2020-08-20
  • 1970-01-01
  • 2021-03-19
  • 2022-11-22
相关资源
最近更新 更多