Created
July 29, 2011 20:01
-
-
Save raichoo/1114605 to your computer and use it in GitHub Desktop.
Multiple dispatch experiment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MMethod[M, A1, A2, R](f: (A1, A2) => R) { | |
def apply(a1: A1, a2: A2): R = f(a1, a2) | |
} | |
class MultiMethod { | |
def apply[A1, A2, R](a1: A1, a2: A2) | |
(implicit mm: MMethod[this.type, A1, A2, R]): R = | |
mm(a1, a2) | |
// use a singleton type to attach the resulting implicit to our multimethod | |
def add[A1, A2, R](f: (A1, A2) => R): MMethod[this.type, A1, A2, R] = | |
new MMethod[this.type, A1, A2, R](f) | |
} | |
case class Asteroid() | |
case class Starship() | |
object Main { | |
val collide = new MultiMethod | |
implicit val mm1 = collide add { | |
(a1: Asteroid, a2: Asteroid) => "Two asteroids collide" | |
} | |
implicit val mm2 = collide add { | |
(s: Starship, a: Asteroid) => "Starship shoots asteroid" | |
} | |
// in soviet russia… | |
val collideInSovietRussia = new MultiMethod | |
// clojure likes mating bunnies | |
implicit val mm3 = collideInSovietRussia add { | |
(a1: Asteroid, a2: Asteroid) => "Two asteroids mate… WTF!?!?!?" | |
} | |
implicit val mm4 = collideInSovietRussia add { | |
(s: Starship, a: Asteroid) => "Asteroid shoots starship… erm yeah… right" | |
} | |
def main(args: Array[String]) { | |
println(collide(Asteroid(), Asteroid())) | |
println(collide(Starship(), Asteroid())) | |
println(collideInSovietRussia(Asteroid(), Asteroid())) | |
println(collideInSovietRussia(Starship(), Asteroid())) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment