1

Written below is a simple scala code.

var variableName:String = "Mickey"
var Mickey:String = "Mouse" 

Is there any way to replace Mickey in the second line by the value of variable variableName? If not, why?

Edit: Although my purpose of asking this question is to understand how/why it can/cannot be done, I would like to write about how I was introduced to this problem. I wrote the following piece of code.

class VertexProperty(var id:Long) extends Serializable

The variable name id is hard-coded here, but I want to put a variable name which gets generated at run-time(for e.g : an input from user).

Below is a pseudo-code which I want to write in scala.

//pseudo-code
1. Ask user for variable's name and type. <user types xyz and String>
2. Define a class with the following definition,
   class VertexProperty(var xyz:String) extends Serializable
  • you could do it the other way around to get the variable name `Mickey` and save it as a string in another variable using **Reflection** – Edwin Jun 22 '16 at 09:47
  • 2
    Why do you need to do this? There are probably better ways to solve your *actual* problem, such as using a `Map`. – Jesper Jun 22 '16 at 10:13
  • 3
    It doesn't make sense, because the name of a variable is just an arbitrary identifier that doesn't mean anything. You could change all variable names in a program to `v0`, `v1`, `v2` and so on, and the program should still work the same. Your idea seems to want to break this assumption. Whatever you want to achieve with this, there should be other and better ways. – Madoc Jun 22 '16 at 11:12
  • I have edited my question. Jesper, that would help, but I want to know whether this can be done. Madoc, very true! But again the same reason. – Anshit Chaudhary Jun 22 '16 at 11:36

1 Answers1

1

I don't think that it can be done (at least easily). See this question: Assigning variables with dynamic names in Java.

Why do you need to do that?

Community
  • 1
  • 1
Simon
  • 6,025
  • 7
  • 46
  • 98