Closed scabug closed 11 years ago
Imported From: https://issues.scala-lang.org/browse/SI-2948?orig=1 Reporter: James Strachan (jstrachan)
@retronym said: We discussed this a little on the lists:
http://old.nabble.com/-scala--Named-parameters-and-default-toString-td26753298.html
http://old.nabble.com/Status-of-existing-feature,-and-proposal-for-new-features-td27066519.html
@paulp said: For the record no new capabilities are necessary. I needed param names for a repl feature, so now there is code to get them. But it's definitely not a supported interface, might be buggy, is sure to change, etc. so it's private[scala]. However if someone wants to write a library, you can see how to go about it. See scala.tools.scalap.Decode.caseParamNames in trunk.
P.S. This is not a reflection hack.
James Strachan (jstrachan) said: @extempore Looking at the code, this looks like it depends on scalap code right? to get the ClassSymbol? I was hoping there would be a simple way to reflect on any case class/Product without requiring bytecode to be parsed with scalap
@dubochet said: I will most likely not implement this enhancement. If someone in the community wants to provide an implementation based on Paul's code (or on another solution), that would be more than welcome.
@retronym said: Closing on the same grounds as #3967.
With macros/reflection, you can opt-in to exposing these names.
What a turn of events 😄
You can introspect using the product* methods on a case class to find element count, their indices and values - but not names. Some would argue the name is way more useful than the index within the class declaration to application programmers.
To be easily be able to convert a case class / Product to/from a Map it would be very handy to be able to look up a product name for a specific index.
We can call productArity to find how many items on a Product/case class, can call productElement(i) to find the value of i - but we can't find the name of element i.
So how about an optional trait NamedProduct which case classes can implement which adds
def productElementName(index: Int) : String
then without doing any hacky reflection hacks (which are quite hard to get right with inheritance and to avoid all the built in methods to be avoided etc), folks can easily turn maps into products and vice versa.
The code generated case class could just have a static lazy value (on the helper object) to lazily calculate it if someone calls productElementName?