Syntactic sugar: Any things in B4X?

alwaysbusy

Expert
Licensed User
Longtime User
I personally do not like inline the ? condition. I see that a lot in JavaScript and it can get messy very quickly.

Anyways, this how Erel solved it:
B4X:
Sub IIF(condition As Boolean, TrueValue As Object, FalseValue As Object)
 If condition Then return TrueValue Else Return FalseValue
End Sub 
'Example
y = IIF(x > 100, 10, x + 10)
 

Emme Developer

Well-Known Member
Licensed User
Longtime User
Anyways, this how Erel solved it:
B4X:
Sub IIF(condition As Boolean, TrueValue As Object, FalseValue As Object)
 If condition Then return TrueValue Else Return FalseValue
End Sub
'Example
y = IIF(x > 100, 10, x + 10)

It's not the same thing. ? operator check if the condition is true. If yes, it evaluates and return the true statement. If not, it evaluates and return false statement. Sub iif instead, evaluates true and false parameters at same time, so if you have a null value in one of the parameter, you will get an Null exception. This mean that you cannot use iif to check if an object is null, and if it has a value then return it.
A small example of what i mean in c#

B4X:
           List<string> lll = null;
            Debug.WriteLine((lll == null) ? "null" : lll[0]);
            Debug.WriteLine(Iff(lll==null, "null", lll[0]));

private string Iff(bool cond, object trueres, object falseres )
        {
            if (cond) return trueres.ToString();
            else falseres.ToString();
            return "";
        }

In first line you will get "null", in second line you get an error
 

wonder

Expert
Licensed User
Longtime User
Last edited:
Top