I want to be able to use the name of my variable programmatically. So, instead of having to give my objects names like this:
case class Server( name: String )
val server = Server("Altair")
println(server)
Which yields: Server("Altair")
or like this:
class Server( name: String ){ override def toString = name }
val server = new Server("Altair")
println(server)
Which yields simply: Altair
I would like something like this:
case class Server extends VariableName
val Altair = new Server
println(Altair)
Which yields simply: Altair
That example shows it as simply a library. It probably can't be done as a library, so it seems like it would have to be a language feature. Something like this.
varname case class Server
val Altair = new Server
println(Altair)
Which yields simply: Altair
Does anything like this exist? Would it be terribly difficult to build into a compiler? Things would probably be tricky if you said something like...
varname case class Server
val Altair = new Server
val Moxy = Altair
println(Moxy)
Would you want to get Altair, or Moxy?
Can anyone give any opinions on this at all?
Jack, maybe this will do:
ReplyDeletetrait Server
case object Altair extends Server
println(Altair) // outputs Altair
Have you tried this?
ReplyDeleteprintln("Altair")
;)
All, maybe I should say more...I guess I'll be specific, and describe my scenario directly, though I'm afraid people might say, "well why would you do that". I do this this idea has wider applications.
ReplyDeleteMy objects are being used to generate an xml configuration that is both consumed by a server on startup, and then later on consumed by devs and QA if a test fails.
The xml contains the following snippet:
<connection name="altair"> ...</connection>
The code itself looks very much like:
val altair = new Connection("altair")
The String is needed in the constructor because it needs to make its way into the xml file. The server spits out the connection name in debug statements, and QA will ask questions about connections with particular names.
You see the redundancy here right?
val altair = new Connection("altair")
I've had to type altair twice. If I had access to the name of the actual val/var, well, that would be really nice.
:)
case object Altair extends Server doesn't really work. The feature I need should work on all vals/vars.
I think it makes sense to have this ability. The programmer types in a variable name in order to specify what the thing is, to give it meaning. Why can't this meaning be more available to all?