【发布时间】:2020-04-14 19:58:27
【问题描述】:
我正在查看Contextual Abstractions 页面下的Dotty 文档,我看到了Given Instances。
给定实例(或简单地说,“给定”)定义“规范”值 用于综合给定子句的参数的某些类型。 示例:
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)
}
}
但是来自docs 的这个示例从未解释如何使用given。我提取了测试Dotty 示例项目并尝试使用它,但我不太了解它。
它是一个新的关键字吗?我们进口它吗?还是我错过了什么。
【问题讨论】:
-
该页面上的first link 解释
-
@JoelBerkeley 我一定是瞎子,因为我没看到:(
标签: scala sbt implicit dotty scala-3