MHJ*_*MHJ 3 scala implicit typeclass dotty scala-3
我正在阅读 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)
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里很困惑,在下面的代码中发生了什么:
given intOrd: Ord[Int] {
def compare(x: Int, y: Int) =
if (x < y) -1 else if (x > y) +1 else 0
}
Run Code Online (Sandbox Code Playgroud)
它是Ord[T]
在given
关键字内实例化还是其他什么?
given
在此上下文中创建Int
typeclass 的成员Ord
并对应于 Scala 2 通过implicit
定义提供 typeclass 实例
implicit object intOrd extends Ord[Int] {
def compare(x: Int, y: Int) =
if (x < y) -1 else if (x > y) +1 else 0
}
Run Code Online (Sandbox Code Playgroud)
如Relationship with Scala 2 Implicits 中所述。
Scala 3 by Example - Philip Schwarz 的更好的 Semigroup 和 Monoid幻灯片对 Scala 2 与 Scala 3 的类型类实现进行了出色的逐步和并排比较,例如,
相关问题:如何使用 Dotty 中的给定?
关于提早提出这个问题的评论,请考虑deusaquilus在Revisiting Implicits 中提出的类似问题
出于好奇,我们是否真的考虑在 Dotty 0.22 和 Scala 3 之间再次更改隐式?我正在尝试衡量功能稳定性,而语法是其中的很大一部分。
奥德斯基答复
就我而言,我希望我们已经达到了一个固定点。我实际上对当前的提案非常满意。如果有人有一个绝妙的主意如何在接下来的几周内进一步改进它的某些方面,我当然很乐意考虑。但我的期望是我们现在大体上完成了。
因此它似乎given
将成为 Scala 3 的一部分。
归档时间: |
|
查看次数: |
783 次 |
最近记录: |