This page is no longer maintained — Please continue to the home page at www.scala-lang.org

"eager" object initialization?

No replies
Landei
Joined: 2008-12-18,
User offline. Last seen 45 weeks 4 days ago.

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

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland