我正在查看页面Dotty
下的文档Contextual Abstractions
,我看到了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 = …
Run Code Online (Sandbox Code Playgroud) 一个非常简单的用例,假设我有一个Foo
接受 2 个参数的类,1 个是普通参数,1 个是隐式参数。
class Foo(val msg: String, implicit val n: Int) {
def multiplier = msg * n
}
implicit val num: Int = 4
val foo = new Foo("yo")
println(foo.msg)
Run Code Online (Sandbox Code Playgroud)
我知道如果我将隐式参数移动到另一个列表(即 curried ),它会起作用class Foo(val msg: String)(implicit val n: Int)
。但是,出于某种原因,我不想这样做。
有人可以解释为什么当前版本的实现不起作用吗?