【发布时间】: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