5

Had a silly question in my head which I hope that someone can answer.

Can we declare id as a variable in Apex? For example: Id id;

I tried to declare the same and Salesforce allowed me to save my class. However when I tried to declare other Primitive types such as String or Date, I got a compile error while saving the class. String string; //compile error Date date; //compile error

These variables are not mentioned in the Salesforce documentation for Reserved keywords(link: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_reserved_words.htm)

Would anyone happen to know if there are any more such variables?

I have a jSON string that I need to deserialize, and that has 'id' as one of its attributes. I would like to understand if there would be any issues if I were to go ahead and create a variable with a name of 'id'

  • I dont know why string, double, integer are not mentioned in reserved keywords... but as I know there is no issue in declaring a variable as 'id'... – Ayub Jan 9 at 18:46
  • Likwise you can create a class with name Id ... public class Id{} ....but you can not do with String .... public class String{} ..... – Ayub Jan 9 at 18:48
3

Id isn't a reserved keyword, and there's no problem using it in wrapper classes, but you should avoid using Id, Account (etc), Schema, etc in classes that have methods, because it will shadow the system class. For example, the following won't compile:

Id Id;
Id v = Id.valueOf('000000000000000');

The same is true for class names, especially top level classes, as it can cause unrelated classes to break unexpectedly. The most common scenario I run across is when a developer names a class Test, which tends to cause all unit tests to fall to compile.

  • +1 from me, though I would say that rather than avoiding using id as a variable name, be aware of the shadowing problem for the rare case where you might use the static valueOf method. – Keith C Jan 9 at 20:02
4

There is no problem using Id as an identifier in Apex. You could run a simple script like the following to verify for yourself:

class Foo
{
    String id;
}

Foo instance = (Foo)JSON.deserialize('{"id": "bar"}', Foo.class);
system.debug(instance.id);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.