Created
August 22, 2011 12:54
-
-
Save missingfaktor/1162307 to your computer and use it in GitHub Desktop.
My take on "Apples to Pears" (without subtyping)
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
// Ref: http://blog.xebia.com/2011/08/comparing-apples-to-pears-in-scala-or-abstract-types-to-the-rescue/ | |
scala> trait Money[C] { | |
| def amount(currency: C): Double | |
| } | |
defined trait Money | |
scala> case class Euro(amount: Double) | |
defined class Euro | |
scala> case class Dollar(amount: Double) | |
defined class Dollar | |
scala> implicit object EuroIsMoney extends Money[Euro] { | |
| def amount(c: Euro) = c.amount | |
| } | |
defined module EuroIsMoney | |
scala> implicit object DollarIsMoney extends Money[Dollar] { | |
| def amount(c: Dollar) = c.amount | |
| } | |
defined module DollarIsMoney | |
scala> implicit def moneyHasOrdering[M : Money] = Ordering by { (m: M) => | |
| implicitly[Money[M]].amount(m) | |
| } | |
moneyHasOrdering: [M](implicit evidence$1: Money[M])scala.math.Ordering[M] | |
scala> val e = implicitly[Ordering[Euro]] | |
e: Ordering[Euro] = scala.math.Ordering$$anon$7@112e9e6 | |
scala> import e._ | |
import e._ | |
scala> Euro(2) > Euro(5) | |
res5: Boolean = false | |
scala> Euro(2) < Euro(5) | |
res6: Boolean = true | |
scala> Euro(3) < Dollar(2) | |
<console>:22: error: type mismatch; | |
found : Dollar | |
required: Euro | |
Euro(3) < Dollar(2) | |
^ | |
scala> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment