- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Scala Ticket #737373
Fri, 2009-02-13, 15:46
Hi,
A year ago or so I submitted issue #737373,
http://lampsvn.epfl.ch/trac/scala/ticket/298.
This issue deals with the fact that the wrong implicit is selected
under certain circumstances. Take a look at the following code:
trait Printer[T] { def print(t: T): String }
implicit val intPrinter = new Printer[Int] {
def print(n: Int) = "n = " + n
}
implicit def listPrinter[T](implicit p: Printer[T]) =
new Printer[List[T]] {
def print(l: List[T]) =
if(l.length == 0) "Empty list"
else l.map(p.print(_)).mkString("[", ", ", "]")
}
def prettyPrint[T](t: T)(implicit p: Printer[T]) = p.print(t)
This works fine, now we can do the following:
scala> prettyPrint(List(42, 66))
res0: String = [n = 42, n = 66]
However, if I would like to add a default printer for types that don't
have an implicit, I would like to do something like this:
implicit def printAny[T] = new Printer[T] {
def print(t: T) = t.toString
}
But if I try to use my prettyPrint method now, printAny will be
selected over printList:
scala> prettyPrint(42)
res2: String = n = 42
scala> prettyPrint(List(42, 66))
res3: String = List(42, 66)
The issue #737373 has been open for a very long time now, and I
understand this might be a hard task to solve, but I would really like
to be able do something like the above. Does anyone know if a solution
to the issue is in sight anytime soon, or is there another way to
implement a "default implicit"?
Regards,
Rickard