Scala 3 — Book

上下文绑定

Language

背景

``````def maxElement[A](as: List[A])(implicit ord: Ord[A]): A =
as.reduceLeft(max(_, _)(ord))
``````
``````def maxElement[A](as: List[A])(using ord: Ord[A]): A =
as.reduceLeft(max(_, _)(using ord))
``````

``````/** Defines how to compare values of type `A` */
trait Ord[A] {
def greaterThan(a1: A, a2: A): Boolean
}

/** Returns the maximum of two values */
def max[A](a1: A, a2: A)(implicit ord: Ord[A]): A =
if (ord.greaterThan(a1, a2)) a1 else a2
``````
``````/** Defines how to compare values of type `A` */
trait Ord[A]:
def greaterThan(a1: A, a2: A): Boolean

/** Returns the maximum of two values */
def max[A](a1: A, a2: A)(using ord: Ord[A]): A =
if ord.greaterThan(a1, a2) then a1 else a2
``````

`max` 方法用了类型为 `Ord[A]` 的上下文参数, 就像 `maxElement` 方法一样。

省略上下文参数

``````def maxElement[A](as: List[A])(implicit ord: Ord[A]): A =
as.reduceLeft(max(_, _))
``````
``````def maxElement[A](as: List[A])(using Ord[A]): A =
as.reduceLeft(max(_, _))
``````

上下文绑定

``````def maxElement[A: Ord](as: List[A]): A =
as.reduceLeft(max(_, _))
``````