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.