Skip to content

Instantly share code, notes, and snippets.

@stew
Created January 20, 2016 23:16
Show Gist options
  • Save stew/52cf742c142144c10b4f to your computer and use it in GitHub Desktop.
Save stew/52cf742c142144c10b4f to your computer and use it in GitHub Desktop.
class Elipse(val width: Double, val height: Double)
// circle is a special case of elispse where width and height are the same
class Circle(r: Double) extends Elipse(r, r)
// typeclass to calculate the Area of a T
trait Area[-T] {
def area(t: T): Double
}
// given a way to calculate the area of a circle (a), determine if the left circle is bigger
def leftIsBiggerCircle(a: Area[Circle])(left: Circle, right: Circle): Boolean = {
val leftArea = a.area(left)
val rightArea = a.area(right)
return leftArea > rightArea
}
// here is a way to calculate the area of any elipse (and remember a circle is an elipse)
val elipseArea = new Area[Elipse] {
def area(e: Elipse): Double = e.height * e.width * 3.14
}
// I can call my leftIsBiggerCircle function using elsipseArea, because Area[Elipse] is a subtype of Area[Circle]
// if you were to redifine Area[-T], as just Area[T], this won't compile
println(leftIsBiggerCircle(elipseArea)(new Circle(2.0), new Circle(1.5)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment