This page is no longer maintained — Please continue to the home page at www.scala-lang.org

implicits lurking in the shadows

No replies
extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.

I wonder what is the current thinking on the issues discussed here:

http://osdir.com/ml/lang.scala.debate/2008-06/msg00097.html

It feels undesirable to me that implicits shadow one another by name. In code that might be used by other
people I am finding myself using method names like orgImprovingEnrichList to be sure to avoid collisions. I
think ad hoc per-programmer namespace invention signals an issue.

A collision is made somewhat more interesting by the fact that the compiler is silent unless you attempt to do
something that requires the shadowed implicit. That means you can import the contents of one object followed
by another, and utilize the implicits in each -- or so you think -- when only the second object's implicits
are used if there is a naming collision. You won't hear from the compiler unless you try to use something it
can't reach. For instance:

object o {
object myClass {
def bloop() = "bye"
implicit def enrichList[T](xs: List[T]) = new RichList(xs)
class RichList[T](xs: List[T]) {
def squawk() = "bwaak!"
def tom() = "I'm just a simple country class."
}
}

object someLibrary {
def bloop() = "hi"
implicit def enrichList[T](xs: List[T]) = new RichList(xs)
class RichList[T](xs: List[T]) {
def squawk() = "chirp!"
def bob() = "I'm an easy to use library from elsewhere. Just import and go!"
}
}

import myClass._
import someLibrary._

// if we use methods in the shadowed enrichment, we'll see the issue...
List("a", "b").bob // ok
List("a", "b").tom // error: value tom is not a member of List[java.lang.String]

// a normal method imported twice is an error (if you call it)...
bloop() // error: reference to bloop is ambiguous

// but implicits are cool with it.
List("a", "b").squawk // ok
}

I realize one could say naming collisions are unlikely (although I don't think they are because of the e.g.
"enrichFoo" conventions already forming) or that people shouldn't promiscuously import implicits (although I
think that would rob library authors of a powerful tool) but unlikely is not really an improvement on likely;
as soon as it might happen, you have to program defensively. There are a lot of ways to shoot yourself in the
foot with implicits, but given present semantics this one looks difficult to avoid completely.

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland