【问题标题】:How does given keyword work in Scala 3 or dotty?给定关键字在 Scala 3 或 dotty 中如何工作?
【发布时间】:2020-05-08 23:21:04
【问题描述】:

我正在浏览 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] 还是其他什么?

【问题讨论】:

  • 问这个问题有点太早了。它还没有最终确定。

标签: scala typeclass implicit dotty scala-3


【解决方案1】:

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 的类型类实现进行了出色的分步和并排比较,例如,

相关问题:How to use given in Dotty?


关于可能提早提出此问题的评论,请考虑deusaquilusRevisiting Implicits 中提出的类似问题

只是出于好奇,我们是否真的在考虑改变隐式 又在 Dotty 0.22 和 Scala 3 之间?我正在尝试衡量功能 稳定性和语法是其中很大一部分。

哪个奥德斯基replies

就我而言,我希望我们已经达到了一个固定点。一世 我实际上对目前的提议非常满意。如果有人有 绝妙的主意如何在未来进一步改进它的某些方面 当然,我很乐意考虑几周。但我的期望是我们 现在基本完成了。

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

【讨论】:

  • Mario 非常感谢您链接到我的幻灯片 :-)
猜你喜欢
  • 2020-04-14
  • 2021-02-05
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 2021-10-04
  • 2019-05-31
  • 2010-09-13
  • 2019-08-07
相关资源
最近更新 更多