Skip to content

Instantly share code, notes, and snippets.

@vvviiimmm
Last active February 19, 2017 19:31
Show Gist options
  • Select an option

  • Save vvviiimmm/c27694faf5c34158ea459885eeb27300 to your computer and use it in GitHub Desktop.

Select an option

Save vvviiimmm/c27694faf5c34158ea459885eeb27300 to your computer and use it in GitHub Desktop.
// Shape is now a parametrized trait
// 'A' is placeholder for `Circle`, `Rectangle` or other shape representation
trait Shape[A] {
def area(a: A): Double
}
case class Circle(radius: Double)
case class Rectangle(width: Double, length: Double)
// We have to extend with Shape[Circle] because we have to pass 'Circle' to `area`
class CircleShape extends Shape[Circle] {
override def area(circle: Circle) : Double = math.Pi * math.pow(circle.radius, 2)
}
// Same here, 'area' takes 'Rectangle'
class RectangleShape extends Shape[Rectangle] {
override def area(rectangle: Rectangle): Double = rectangle.width * rectangle.length
}
// vvv (hmmm)
def areaOf[A](shape: Shape[A]): Double = shape.area(???)
areaOf(new CircleShape)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment