9

Is there any reason to use one over the other? Efficiency? "gotcha's"?

I am working on a major code cleanup, and my org is littered with both types, so as I'm going through, I'd like to standardize, but don't yet know/care which one. If there's an efficiency gain for one over the other, I'd like to take advantage of it, otherwise I'll choose the one that simply makes things easier to read...

1 Answer 1

8

Casting only works when the variable you are trying to cast is of the type you are trying to cast it to. Boolean.valueOf() is more flexible, working on both Strings and Booleans.

It should be safe to convert (Boolean) => Boolean.valueOf(), but changing Boolean.valueOf() => (Boolean) could be problematic.

//Works
String tester = 'test';
Boolean result = Boolean.valueOf(tester);
System.assertEquals(false, result);

//Fails - System.TypeException: Invalid boolean or String: 0
Integer tester = 0;
Boolean result = Boolean.valueOf(tester);

//Works
Object tester = false;
Boolean result = (Boolean) tester;
System.assertEquals(false, result);

//Fails - Incompatible types since an instance of String is never an instance of Boolean
String tester = 'test';
Boolean result = (Boolean) tester;

I don't think there is any significant performance difference between the two.

1
  • Fair point on the original type. Definitely safer to use the .valueOf() in case of any data idiosyncracies. Jun 28, 2015 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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