This is the code for the blog entry implicit double dispatch.
package michid;
object Converters {
abstract class Dispatcher[T](value: T) {
def select(switch: Switch)
def dispatch(switch: Switch)
}
implicit def string2Disp(value: String) = new Dispatcher(value){
def select(switch: Switch) {}
def dispatch(switch: Switch) {
switch.case_(value)
}
}
implicit def int2Disp(value: int) = new Dispatcher(value){
def select(switch: Switch) {}
def dispatch(switch: Switch) {
switch.case_(value)
}
}
implicit def list2Disp[T](value: List[T])(implicit x2Disp: T => Dispatcher[T]) = new Dispatcher(value) {
def select(switch: Switch) {
for(x <- value) {
x2Disp(x).dispatch(switch)
}
}
def dispatch(switch: Switch) {}
}
trait Switch {
def case_(s: String)
def case_(n: int)
}
}
object Poly {
import michid.Converters._
def foo[T <% Dispatcher[T]](x: T) {
x.select(new Switch {
def case_(x: String) {
println("Got a string " + x)
}
def case_(x: int) {
println("Got a int " + x)
}
})
}
def main(args: Array[String]) {
foo("11"::"12"::Nil)
foo(12::5::Nil)
//foo(12.0::5::Nil) Does not compile!
}
}
[...] Implicit double dispatch 18 01 2008 While playing around with JCR and Scala I stumbled over JCR’s Value type. I wanted to be able to handle it in a type safe way by using Scala’s generics. This was not a problem until it came to collection of values. Here is a boiled down version of my problem not directly related to JCR. (The entire code is available on my code page under implicit double dispatch. [...]
[...] generalized my initial code to address these issues. The revisited code is again available on my code [...]