给定关键字在 Scala 3 或 dotty 中如何工作?

How does given keyword work in Scala 3 or dotty?

我正在浏览 Scala 3 文档。他们引入了 given 关键字,它被认为是 Scala 2 implicit 的替代品。 代码在这里

trait Ord[T] {
  def compare(x: T, y: T): Int
  def (x: T) < (y: T) = compare(x, y) < 0
  def (x: T) > (y: T) = compare(x, y) > 0
}

given intOrd: Ord[Int] {
  def compare(x: Int, y: Int) =
    if (x < y) -1 else if (x > y) +1 else 0
}

given listOrd[T]: (ord: Ord[T]) => Ord[List[T]] {

  def compare(xs: List[T], ys: List[T]): Int = (xs, ys) match {
    case (Nil, Nil) => 0
    case (Nil, _) => -1
    case (_, Nil) => +1
    case (x :: xs1, y :: ys1) =>
      val fst = ord.compare(x, y)
      if (fst != 0) fst else compare(xs1, ys1)
  }
}

我很困惑下面代码中发生了什么:

given intOrd: Ord[Int] {
   def compare(x: Int, y: Int) =
   if (x < y) -1 else if (x > y) +1 else 0
}

它是在 given 关键字内实例化 Ord[T] 还是其他?

given 在此上下文中使 Int 成为类型类 Ord 的成员,对应于 Scala 2 通过 implicit 定义

提供类型类实例
implicit object intOrd extends Ord[Int] {
  def compare(x: Int, y: Int) =
    if (x < y) -1 else if (x > y) +1 else 0
}

Relationship with Scala 2 Implicits 中所述。

Scala 3 by Example - better Semigroup and Monoid Philip Schwarz 的幻灯片对类型类的 Scala 2 与 Scala 3 实现进行了出色的逐步和并排比较,例如,

相关问题:


关于评论可能提早提出这个问题,请考虑 deusaquilus in Revisiting Implicits

的类似问题

Just out of curiosity, are we actually considering changing implicits again between Dotty 0.22 and Scala 3? I’m trying to gauge feature stability and syntax is a large part of that.

奥德斯基 replies

As far as I am concerned I hope that we have reached a fixed point. I am actually quite happy with the current proposal. If someone has a brilliant idea how to improve some aspect of it further over the next weeks I am happy to consider, of course. But my expectation is that we are by and large done now.

因此 given 似乎将成为 Scala 3 的一部分。