问题
I was going through Scala 3 documentation. They have introduced given
keyword which is considered as the alternative of Scala 2 implicit
.
The code is here
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)
}
}
I am very confused here that what is happening here in the bellow code:
given intOrd: Ord[Int] {
def compare(x: Int, y: Int) =
if (x < y) -1 else if (x > y) +1 else 0
}
Is it instantiating Ord[T]
within given
keyword or something else?
回答1:
given
is in this context making Int
a member of typeclass Ord
and corresponds to Scala 2 providing a typeclass instance via implicit
definition
implicit object intOrd extends Ord[Int] {
def compare(x: Int, y: Int) =
if (x < y) -1 else if (x > y) +1 else 0
}
as explained in Relationship with Scala 2 Implicits.
Scala 3 by Example - better Semigroup and Monoid slides by Philip Schwarz have excellent step-by-step and side-by-side comparisons of Scala 2 versus Scala 3 implementations of typeclasses, for example,
Related question: How to use given in Dotty?
Regarding the comment it might early to ask this question, consider similar question by deusaquilus in Revisiting Implicits
Just out of curiosity, are we actually considering changing implicits again between Dotty 0.22 and Scala 3? I’m trying to gauge feature stability and syntax is a large part of that.
to which Odersky replies
As far as I am concerned I hope that we have reached a fixed point. I am actually quite happy with the current proposal. If someone has a brilliant idea how to improve some aspect of it further over the next weeks I am happy to consider, of course. But my expectation is that we are by and large done now.
Thus it seems given
will be part of Scala 3.
来源:https://stackoverflow.com/questions/59865815/how-does-given-keyword-work-in-scala-3-or-dotty