Implicit double dispatch

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! } } [/sourcecode]

2 responses

18 01 2008
Implicit double dispatch « Michid’s Weblog

[…] 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. […]

13 08 2008
Implicit double dispatch revisited « Michid’s Weblog

[…] generalized my initial code to address these issues. The revisited code is again available on my code […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: