Skip to content

Instantly share code, notes, and snippets.

@rsuniev
Forked from debasishg/gist:892300
Created March 29, 2011 13:04
Show Gist options
  • Save rsuniev/892312 to your computer and use it in GitHub Desktop.
Save rsuniev/892312 to your computer and use it in GitHub Desktop.
case class ElectricCar(b: Battery) { def batteryLevel = b.filledPercentage }
case class GasolineCar(g: GasTank) { def gasLevel = g.filledPercentage }
case class Battery(filledPercentage: Int) { def fill: Battery = Battery(100) }
case class GasTank(filledPercentage: Int) { def fill: GasTank = GasTank(100) }
trait Fills[C] {
def fill(car: C): C
}
trait Implicits {
implicit object ElectricCarFills extends Fills[ElectricCar] {
def fill(car: ElectricCar) =
if (car.batteryLevel < 100) ElectricCar(car.b.fill) else car
}
implicit object GasolineCarFills extends Fills[GasolineCar] {
def fill(car: GasolineCar) =
if (car.gasLevel < 100) GasolineCar(car.g.fill) else car
}
}
object Implicits extends Implicits
object Fill {
def fill[C](car: C)(implicit f: Fills[C]) = f.fill(car)
}
import Implicits._
import Fill._
val eCar = ElectricCar(Battery(25))
fill(eCar).batteryLevel == 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment