Reputation: 903
Has anyone found a way to declare variables on the fly?
I have some variables that can be limitless...
val1
val2
val3
val4...
Is there a way to create these on the fly, something like...
for(loop though){
val + '1' = dosomething('1')
}
I know it wont look anything like the above, but hoping you get the gist of it.
Upvotes: 1
Views: 1499
Reputation: 11600
This isn't possible in apex. You could however use a list:
List<String> values = new List<String>();
for (Integer i = 0; i < aList.size(); i++) {
values.add(dosomething(i));
}
Upvotes: 1
Reputation: 19622
Apex is a compiled, not parsed / dynamic language. You could pull such thing off in say Javascript or PHP but (as far as I know) not in Java. And when you get to the bottom of it - Salesforce is built on Oracle database and Java so Apex is kind of thin wrapper on Java calls they deemed most necessary.
Just out of curiosity - why would you need that?
Use Jeremy's idea with loops if you need sequential access. Or...
If you need "unique key -> some value", use Maps.
Map<String, Double> myMap = new Map<String, Double>();
for(Integer i = 1; i < 10; ++i){
myMap.put('someKey' + String.valueOf(i),Math.floor(Math.random() * 1000));
}
System.debug(myMap);
System.debug(myMap.get('someKey7'));
The "double" in this example can be equally Integer, Id, Account, MyCustomClass... whatever your function returns.
There's one more trick I can think of that might be helpful if your data comes from external source. It's to use JSON / XML parsers that could cast any kind of data (held in a String) to a collection of your choice. It kind of goes back to List/Map idea but it's totally up to you how would you build / retrieve this string beforehand. Read about JSON methods for a start although if you don't have a structure that follows predictable pattern you might want to check out JSON/XML parsers (click here and scroll down to the examples).
Upvotes: 1