-
-
Save rsuniev/892312 to your computer and use it in GitHub Desktop.
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
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