Sometimes we want an optional parameter
function doSomething(foo:Integer; bar:TObject=nil)
begin
if bar <> nil then // do something optional with bar
....
end
How do I do the equivalent with a boolean, that allows me to differentiate between the two boolean values and "no value"?
function doSomething(foo:Integer; bar:Boolean=nil) // Won't compile
begin
if bar <> nil then // do something optional with bar
end
Obviously this won't compile as a Boolean cannot be nil.
Basically, I want a parameter with three possible states; true, false or "unspecified".
static Boolean valueOf(boolean b) : This method returns a Boolean instance representing the specified boolean value. If the specified boolean value is true, it returns Boolean. TRUE or if it is false, then this method returns Boolean.
public final class OptionalBoolean extends Object. A container object which may or may not contain a boolean value. If value is present, isPresent() will return true and getAsBoolean() will return the value.
The Python Boolean type is one of Python's built-in data types. It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False .
You can use the bool method to cast a variable into Boolean datatype. In the following example, we have cast an integer into boolean type. You can also use the bool method with expressions made up of comparison operators. The method will determine if the expression evaluates to True or False.
You can do this other way, using overloading:
function doSomething(foo:Integer): Boolean; overload;
begin
// do something without bar
end;
function doSomething(foo:Integer; bar:Boolean): Boolean; overload
begin
// do something optional with bar
end;
Then you can use it as doSomething(1)
, as well as doSomething(1, true)
Using your example, it will be equivalent to:
function doSomething(foo:Integer; bar:Boolean=nil): Boolean; // Won't compile
begin
if bar <> nil then
// do something optional with bar
else
// do something without bar
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With