Skip to content

Instantly share code, notes, and snippets.

@huitseeker
Last active December 19, 2015 05:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huitseeker/5901666 to your computer and use it in GitHub Desktop.
Save huitseeker/5901666 to your computer and use it in GitHub Desktop.
Triggering Implicit search by emulating double dispatch using simple dispatch
object Point {
trait PointAdder[P2] {
def add(p2: P2): Point3D
}
case class Point2D(x: Int, y: Int)
case class Point3D(x: Int, y: Int, z: Int)
implicit class Point2Adder(p1:Point2D) extends PointAdder[Point2D] {
def add(p2: Point2D): Point3D = Point3D(p1.x + p2.x, p1.y + p2.y, 0)
}
implicit class Point3DAdder(p1:Point3D) extends PointAdder[Point3D] {
def add(p2: Point3D): Point3D = Point3D(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z)
}
implicit class Point2DPoint3DAdder(p1:Point2D) extends PointAdder[Point3D] {
def add(p2: Point3D): Point3D = Point3D(p1.x + p2.x, p1.y + p2.y, p2.z)
}
implicit class Point3DPoint2DAdder(p1:Point3D) extends PointAdder[Point2D] {
def add(p2: Point2D): Point3D = Point3D(p1.x + p2.x, p1.y + p2.y, p1.z)
}
def main(args: Array[String]) {
val point1 = Point2D(1, 2)
val point2 = Point3D(1, 2, 3)
println(point1.add(point2))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment