Honestly I don’t find the syntax great. given
doesn’t seem to give us anything that implicit
doesn’t: if we find-and-replace all the given
s with implicit
s, we’d get all the benefits and much less disruption. The usage of :
, and how strongly it binds left and right, also goes against what someone programming in Scala would expect.
Some more specific issues:
- This syntax is pretty confusing: it looks like some kind of refinement type, but it isn’t:
given intOrd: Ord[Int] {
def compare(x: Int, y: Int) =
if (x < y) -1 else if (x > y) +1 else 0
}
If Scala didn’t have refinement types maybe this could be ok, but as is I find this extremely hard to parse. And the precedence is all wrong: normally {
has higher precedence than :
, but here it’s reversed.
- I also think the anonymous
given
instances look much worse than what we currently have with implicits:
given Ord[Int] { ... }
given [T](given Ord[T]): Ord[List[T]] { ... }
Neither of these look particularly good. The top one has a type expression in a place that looks like no other language construct in existence, while the bottom looks like keyword soup with the two given
s that do not match to any normal english usage of the word.
- Alias
given
s honestly would look fine as implicit
given global: ExecutionContext = new ForkJoinPool()
implicit global: ExecutionContext = new ForkJoinPool()
In fact, that’s almost the syntax now! We just need to make the def
/val
/lazy val
optional, and we’re done.
- I am personally not a huge fan of the extension method syntax. The precedence between
given
, :
, extension
and {
seems all wrong in the given examples
given stringOps: extension (xs: Seq[String]) {
def longestStrings: Seq[String] = {
val maxLength = xs.map(_.length).max
xs.filter(_.length == maxLength)
}
}
Overall the usage of :
in the given
syntax doesn’t work out. It looks too much like something we’re already familiar with, and comes with baggage of the precedence we’re already used to, but is parsed in a totally different way. Using a new keyword would be far better than overloading :
in this way