Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an optional boolean variable

Tags:

delphi

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".

like image 515
awmross Avatar asked Sep 22 '11 01:09

awmross


People also ask

How do you pass a boolean value?

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.

What is optional 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.

How do you pass a boolean value in Python?

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 .

How do you assign a boolean to a variable?

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.


1 Answers

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;
like image 194
Serhii Kheilyk Avatar answered Sep 30 '22 23:09

Serhii Kheilyk