- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
"eager" object initialization?
Mon, 2009-06-29, 09:34
Hi!
I try to get the advantages both of the Enumeration class and of the "case
object enum pattern". It would work fine if I could find a way to get that
stupid lazy objects initializing without having to call them first:
sealed abstract class TrafficLight {
//this could go later in a common Enum superclass
TrafficLight.map += getClass.getName.split('$')(1) -> this
}
object TrafficLight {
object RED extends TrafficLight
object YELLOW extends TrafficLight
object GREEN extends TrafficLight
//this could go later in a common EnumObject superclass
private var map=Map[String,TrafficLight]()
def names = map.keys.toList
def apply(name:String) = map.get(name)
}
object enums {
def main(args:Array[String]) {
/////////////////////////////////////////////
/// How to get rid of this?
/////////////////////////////////////////////
TrafficLight.RED
TrafficLight.YELLOW
TrafficLight.GREEN
////////////////////////////////////////////
//works as expected
println(TrafficLight.names)
println(TrafficLight("RED") == Some(TrafficLight.RED))
}
}
*I* am the programmer, so *I* am supposed to be lazy, right? Any ideas?
Cheers,
Daniel