I would like to be able to apply the pimp-my-library pattern to state, rather than behavior. Specifically, if you define a var in an implicit def, set it, and then try to read it, the state is lost. I’ve thrown together a contrived example:
class Planet(val name: String)
object SolarSystem {
val Mercury = new Planet("Mercury")
val Venus = new Planet("Venus")
val Earth = new Planet("Earth")
val Mars = new Planet("Mars")
val Jupiter = new Planet("Jupiter")
val Saturn = new Planet("Saturn")
val Uranus = new Planet("Uranus")
val Neptune = new Planet("Neptune")
val Pluto = new Planet("Pluto")
}
object Pimper {
implicit def pimpPlanet(planet: Planet) = {
new {
var distanceFromSun: Int = 0
}
}
import SolarSystem._
Jupiter.distanceFromSun = 5 // AU
}
object Main {
def main(args: Array[String]) {
import SolarSystem._
import Pimper._
println(Jupiter.distanceFromSun)
}
}
Naturally, this will print 0, but I’d like it to print 5. I’ve considered a handful of solutions, including extending SolarSystem and overriding what Jupiter is, or having a map outside that’s populated/read by a getter & setter.
I’m pretty new to Scala, and I was hoping there was a more elegant way to go about doing something like this. Also yes, Pluto is a planet 🙂
1 Answer