+ Start a Discussion

Behavior of Boolean.valueOf

In my code I want to replace the following where I am checking the value of a formula field (of type text) that refers to a checkbox field. The fomula field returns 'true' or 'false' based on the checkbox being checked or unchecked.



if ('true' == <MysObject>.Is_Range_Constrained__c) {...}


if (Boolean.valueOf(<MysObject>.Is_Range_Constrained__c)) {...}


The problem is the API docs do not explicitly say what is valid arguments for Boolean.valueOf(...) and the expected return values and I do not want to use something that is not documented in case the behavior changes or is specified in a future release.


Does anyone know if the code below is the expected behavior of Boolean.valueOf(...) on SFDC and is it documented somewhere? The behavior I get by trial and error is roughly in line with what Java would return.


By trial and error I get the following:

System.debug('=======> ' + Boolean.valueOf('true')); .. returns true

System.debug('=======> ' + Boolean.valueOf('True')); .. returns true

System.debug('=======> ' + Boolean.valueOf('TRUE')); .. returns true

System.debug('=======> ' + Boolean.valueOf('false')); .. returns false

System.debug('=======> ' + Boolean.valueOf('False')); .. returns false

System.debug('=======> ' + Boolean.valueOf('FALSE')); .. returns false

System.debug('=======> ' + Boolean.valueOf('')); .. returns false

System.debug('=======> ' + Boolean.valueOf('nnnn')); .. returns false

System.debug('=======> ' + Boolean.valueOf(0)); .. System.TypeException: Invalid boolean or String: 0

System.debug('=======> ' + Boolean.valueOf(1)); .. System.TypeException: Invalid boolean or String: 1

System.debug('=======> ' + Boolean.valueOf(10)); .. System.TypeException: Invalid boolean or String: 10


Is your <MysObject>.Is_Range_Constrained__c a checkbox field or a text field?


If it is a text field then I can guarantee what you are suggesting will work.  If it is a checkbox field you can simply go:


if (<MysObject>.Is_Range_Constrained__c) {...}


I believe the integer may actually work in apex, but if you know you are passing in a string to the method then it shouldn't be an issue.:




Boolean fields have one of these values: true (or 1), or false (or 0).


Thanks but I may have not have stated my problem clearly but basically is there any documentation that states Boolean.valueOf('true') == true and Boolean.valueOf('nnn') == false.


I couldn't find any.  Why don't you just that in code really quick and see what happens.