function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Alan Mc CarthyAlan Mc Carthy 

How to assign a value to a boolean variable based on multiple conditions, without IF statements.

Hey guys, I have a boolean variable called myBool. I want myBool to be true if conditions A, B and C are all met, and false otherwise. The easy way is to declare myBool and leave it null, create an if statement, and update the value of myBool to true or false based on the results of the if statement.

For the sake of prettier and less cumbersome code, I was wondering if there is a method you can call which acts like the Salesforce formula function 'AND'. The way AND works is that you give it some boolean arguments and if every argument evaluates to TRUE, then the whole AND function evaluates to TRUE. What is handy about this is that the arguments can be equations... so you could have something like : AND( 1 + 1 = 2, 2 + 2 = 4), and this would equal TRUE.

So is there a way to do this using Apex? The exact use case, if it helps to understand my question, is the following: I want to be able to write the following code: Boolean myBool = (equation). For equation I would like to insert a value on each side and see if they are the same (and the values could be any data type). If the values are the same, then myBool would be TRUE.

Any help would be greatly appreciated!
 
Best Answer chosen by Alan Mc Carthy
Arpit Jain7Arpit Jain7
Hello Alan,

You can simply try something like below in your apex class

Boolean myBool = 1+1==2 && 2+2==4?True:False

Thanks
Arpit

All Answers

Arpit Jain7Arpit Jain7
Hello Alan,

You can simply try something like below in your apex class

Boolean myBool = 1+1==2 && 2+2==4?True:False

Thanks
Arpit
This was selected as the best answer
Alan Mc CarthyAlan Mc Carthy
Hi Arpit,

That is exactly what I was looking for. I wasn't aware of that syntax! Thanks very much for your quick response.

Alan