Wish Ternary Operators

Computersmith64

Well-Known Member
Licensed User
Longtime User
It would be great if B4X supported ternary operators so we could do inline if statements. Consider this scenario:

I have a SQLite database table that I want to store a boolean value in. SQLite doesn't support booleans, so I have to use an integer type for the field, then convert int values pulled from the database to boolean & vis-a-vis when saving values to the table. So one way to do this is:
B4X:
Private Sub dbStuff
    ...
    Private boolVal = toBool(Cursor.GetInt("boolasint"))
    ....
    SQL1.ExecNonQuery($"UPDATE table SET boolasint=${fromBool(boolVal)} WHERE..."$
End Sub


Private Sub toBool(val as Int) as Boolean
    If val = 0 Then Return False Else Return True
End Sub

Private Sub fromBool(val as Boolean) as Int
    If val Then Return 1 Else Return 0
End Sub

However it would be much easier & more efficient if I could just write:
B4X:
Private Sub sbStuff
    ...
    Private boolVal = Cursor.GetInt("boolasint") = 0 ? False : True 
    ....
    SQL1.ExecNonQuery($"UPDATE table SET boolasint=${boolval = True ? 1 : 0} WHERE..."$

'(or even better)

    SQL1.ExecNonQuery($"UPDATE table SET boolasint=${boolval ? 1 : 0} WHERE..."$
End Sub

- Colin.
 

DPaul

Active Member
Licensed User
Longtime User
I am sticking my neck out here, very new on the block,
but i just tested this, and it works:
Dim s As String = "False"
Dim b As Boolean = True
b = s
If not(b) Then Msgbox("This works", "...")

So, if you have s(0) = "False" and s(1) = "True"
you could use your retrieved s(cursor.GetInt("boolasint")) as index and save some code.

(Waiting for experts to tell me wrong)
DPaul
 

Roycefer

Well-Known Member
Licensed User
Longtime User
The examples you gave can be streamlined without the ternary operator.
B4X:
Private Sub sbStuff
    Private boolVal As Boolean = Cursor.GetInt("boolasint")==1
    SQL1.ExecNonQuery($"UPDATE table SET boolasint=${IIF(boolVal,1,0)}....
End Sub

Public Sub IIF(condition As Boolean, TrueValue As Object, FalseValue As Object) As Object
    If condition Then Return TrueValue
    Return FalseValue
End Sub

The real strength of a ternary operator is when you want to enforce lazy evaluation. For example
B4X:
Dim x As Double = IIF(y<>0, 100/y, 100)
will cause a divide-by-zero Exception when y==0 because the 100/y argument is evaluated regardless of the truthiness of y<>0. In this case, we really do need a ternary operator to get all this on one line without Exceptions:
B4X:
Dim x As Double = y<>0 ? 100/y : 100
Another example is when evaluating one of the arguments entails a very lengthy (and potentially unnecessary) calculation or DB access. However, if your scenario doesn't demand lazy evaluation, you can accomplish it with the IIF function (or something like it).
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…