-1

I have an object

object Helper{
val fieldName = "fooBar
}

which provides the name for a field. And a case class

case class BarBaz(fieldOne:Int, fieldTwo:String)

But instead of fieldTwo, I would like to refer to Helper.fieldname for the parameter name of the case class.

How can this be accomplished in Scala? Maybe via a macro? Or is there a simpler possibility? I.e.

case class BarBaz(fieldOne:Int, Helper.fieldName:String)

would be the desired output, but that will not compile.

Georg Heiler
  • 16,916
  • 36
  • 162
  • 292
  • calling as BarBaz.fieldTwo or Helper.fieldName, aren't they the same? You have to create instance of both. Can you not change the field name of case class? – Ramesh Maharjan Jun 11 '17 at 11:14
  • I want to be able to change the field name of the case class by modifying the val `fieldName`. Please see the edit. – Georg Heiler Jun 11 '17 at 11:15
  • Not sure what you're trying to accomplish here, but `Map[String, ?]` may be a simpler way to access things by means of a "dynamic identifier". – rethab Jun 11 '17 at 12:00
  • I need a case class for spark dataset to work. And this case class should be constructed at compile time to have an attribute of name Helper.fieldName – Georg Heiler Jun 11 '17 at 12:11
  • Could you please provide code snippet which you struggling with in relation to Spark, I would really assume your issue has nothing to do with dynamic field name creation etc. Thanks – Pavel Jun 11 '17 at 12:26
  • It doesn't need to be runtime. Compile time and a macro are fine as well – Georg Heiler Jun 11 '17 at 12:33

1 Answers1

1

I don't think its possible as defining variables means pointing to some memory location where the value is stored. So the compiler sees a variable name as memory location address and not the value stored in that location and using a memory location for a variable name would not be allowed.

Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97