[SalesForce] the difference between (Id)str and Id.valueOf(str)

Say I have one string String strId = 001xa000003DIlo and I want to typecast it to an Id. So I have two options to do so:

  1. Id idVal = (Id)strId;
  2. Id idVal = Id.valueOf(strId);

Which is the best way to achieve this purpose?

What exactly is the difference between these two approaches?

Is the difference same for typecasting a String, Decimal or any other datatype?

Best Answer

The first is casting. The second is calling a static method on the Id class.

One major advantage of the former is that it is more null safe.

Id idVal1 = (Id)null; // works
Id idVal2 = Id.valueOf(null); // blows up

One advantage of the latter is that you can one-line more of your code by calling instance methods on the cast result. You can get one-liners by adding some parentheses to the casting approach, though some might object on stylistic grounds. I find it a little more visually confusing.

SObjectType t1a = (Id)'001000000000000AAA'.getSObjectType(); // blows up
SObjectType t1b = ((Id)'001000000000000AAA').getSObjectType(); // works
SObjectType t2 = Id.valueOf('001000000000000AAA').getSObjectType(); // works

The above pros/cons are independent of type, so you can carry these conclusions over to String, Decimal, etc.