Skip to content

Instantly share code, notes, and snippets.

@lylek
Created March 18, 2015 01:13
Show Gist options
  • Save lylek/08cf5e892e8e37ebda73 to your computer and use it in GitHub Desktop.
Save lylek/08cf5e892e8e37ebda73 to your computer and use it in GitHub Desktop.
Asteroid vs. Spaceship
class Asteroid
class Spaceship
trait Collidable[A, B] {
def collideWith(a: A, b: B): String
}
implicit object CollidableAsteroidWithAsteroid extends Collidable[Asteroid, Asteroid] {
def collideWith(a: Asteroid, b: Asteroid) =
"what happens when an asteroid collides with an asteroid"
}
implicit object CollidableAsteroidWithSpaceship extends Collidable[Asteroid, Spaceship] {
def collideWith(a: Asteroid, b: Spaceship) =
"what happens when an asteroid collides with a spaceship"
}
implicit object CollidableSpaceshipWithAsteroid extends Collidable[Spaceship, Asteroid] {
def collideWith(a: Spaceship, b: Asteroid) =
"what happens when a spaceship collides with an asteroid"
}
implicit object CollidableSpaceshipWithSpaceship extends Collidable[Spaceship, Spaceship] {
def collideWith(a: Spaceship, b: Spaceship) =
"what happens when a spaceship collides with a spaceship"
}
def collideWith[A, B](a: A, b: B)(implicit ev: Collidable[A, B]): String =
ev.collideWith(a, b)
val a1 = new Asteroid
val a2 = new Asteroid
val s1 = new Spaceship
val s2 = new Spaceship
// Static dispatch only
println(collideWith(a1, s1))
println(collideWith(s2, s1))
class BlueAsteroid extends Asteroid
// leads to an error: could not find implicit value for parameter ev
println(collideWith(new BlueAsteroid, s1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment