Sub Save (user_id As Int, user_name As String, user_age As Int, user_email As String, user_password As String, user_occupation As String)
End Sub
Save(1, "John Cena", 21, "", "", "")
Save(1, "John Cena")
Type User (user_id As Int, user_name As String, user_age As Int, user_email As String, user_password As String, user_occupation As String)
Sub CreateUser(user_id As Int, user_name As String = "NoName", user_age As Int = 21, user_email As String = "", user_password As String = "default", user_occupation As String = "Actor")
End Sub
CreateUser (1, "John Cena")
Private Sub ShowMessage(Text As String, Title As String, Duration As Int)
Log(Title & ": " & Text)
End Sub
ShowMessage("Connection successful", "Bluetooth", 2000)
Private Sub ShowMessage(Text As String, _
Title As String = "Information", _
Duration As Int = 2000)
Log(Title & ": " & Text)
End Sub
ShowMessage("Connection successful")
ShowMessage("Connection successful", "Information", 2000)
ShowMessage("Connection successful", "Bluetooth")
ShowMessage("Battery critically low", "Warning", 5000)
Private Sub CalculatePrice(Price As Double, _
TaxRate As Double = 0.095, _
Discount As Double = 0) As Double
Return (Price - Discount) * (1 + TaxRate)
End Sub
Dim Total1 As Double = CalculatePrice(100)
Dim Total2 As Double = CalculatePrice(100, 0.08)
Dim Total3 As Double = CalculatePrice(100, 0.08, 10)
'Uses TaxRate = 0.095 and Discount = 0
Dim Total1 As Double = CalculatePrice(100)
'Uses TaxRate = 0.08 and Discount = 0
Dim Total2 As Double = CalculatePrice(100, 0.08)
'Uses TaxRate = 0.08 and Discount = 10
Dim Total3 As Double = CalculatePrice(100, 0.08, 10)
= is what makes the parameter optional.Private Sub SendCommand(Command As String, _
Timeout As Int = 5000, _
RetryCount As Int = 3)
End Sub
Command is required.Timeout is optional.RetryCount is optional.Private Sub SendCommand(Command As String, _
Timeout As Int = 5000, _
DeviceId As String)
End Sub
DeviceId is required but appears after an optional parameter.Private Sub SendCommand(Command As String, _
Timeout As Int = 5000, _
RetryCount As Int = 3, _
WriteLog As Boolean = True)
'Send the command...
End Sub
SendCommand("MOVE")
SendCommand("MOVE", 10000)
SendCommand("MOVE", 10000, 5)
SendCommand("MOVE", 10000, 5, False)
'Currently not supported:
SendCommand("MOVE", , , False)
WriteLog is changed more frequently than the timeout, this order may be better:Private Sub SendCommand(Command As String, _
WriteLog As Boolean = True, _
Timeout As Int = 5000, _
RetryCount As Int = 3)
'Send the command...
End Sub
SendCommand("MOVE", False)
Private Sub WriteCharacteristic(CharacteristicUUID As String, _
Data() As Byte, _
WithResponse As Boolean, _
TimeoutMs As Int, _
LogPacket As Boolean) As ResumableSub
'Perform BLE write...
Return True
End Sub
Wait For (WriteCharacteristic(ChairMotionCMD_UUID, _
Array As Byte(0x01), True, 5000, True)) _
Complete (Success As Boolean)
WithResponse = TrueTimeoutMs = 5000LogPacket = TruePrivate Sub WriteCharacteristic(CharacteristicUUID As String, _
Data() As Byte, _
WithResponse As Boolean = True, _
TimeoutMs As Int = 5000, _
LogPacket As Boolean = True) As ResumableSub
If LogPacket Then
Log($"Writing ${Data.Length} bytes to ${CharacteristicUUID}"$)
End If
'Perform BLE write...
Return True
End Sub
Wait For (WriteCharacteristic(ChairMotionCMD_UUID, _
Array As Byte(0x01))) Complete (Success As Boolean)
Wait For (WriteCharacteristic(ChairMotionCMD_UUID, _
Array As Byte(0x01), False, 10000, False)) _
Complete (Success As Boolean)
Private Sub SendApiRequest(Url As String, _
Method As String, _
Body As String, _
Headers As Map, _
Timeout As Int) As ResumableSub
Wait For (SendApiRequest(ApiUrl, "GET", "", Null, 30000)) _
Complete (Response As String)
Private Sub SendApiRequest(Url As String, _
Method As String = "GET", _
Body As String = "", _
Headers As Map = Null, _
Timeout As Int = 30000) As ResumableSub
Dim Job As HttpJob
Job.Initialize("", Me)
Select Method.ToUpperCase
Case "GET"
Job.Download(Url)
Case "POST"
Job.PostString(Url, Body)
Case "PUT"
Job.PutString(Url, Body)
Case "DELETE"
Job.Delete(Url)
End Select
If Headers <> Null Then
For Each Key As String In Headers.Keys
Job.GetRequest.SetHeader(Key, Headers.Get(Key))
Next
End If
Job.GetRequest.Timeout = Timeout
Wait For (Job) JobDone(Job As HttpJob)
Dim Result As String = ""
If Job.Success Then
Result = Job.GetString
End If
Job.Release
Return Result
End Sub
Wait For (SendApiRequest(ApiUrl)) Complete (Response As String)
Wait For (SendApiRequest(ApiUrl, "POST", JsonBody)) _
Complete (Response As String)
Dim Headers As Map = CreateMap( _
"Authorization": "Bearer " & Token, _
"Content-Type": "application/json")
Wait For (SendApiRequest(ApiUrl, "POST", JsonBody, Headers, 60000)) _
Complete (Response As String)
Private Sub CreateStyledButton(Text As String, _
Width As Int, _
Height As Int, _
BackgroundColor As Int, _
TextColor As Int, _
FontSize As Float) As B4XView
Dim ConnectButton As B4XView = CreateStyledButton( _
"Connect", 160dip, 50dip, 0xFF1976D2, _
xui.Color_White, 16)
Private Sub CreateStyledButton(Text As String, _
Width As Int = 160dip, _
Height As Int = 50dip, _
BackgroundColor As Int = 0xFF1976D2, _
TextColor As Int = 0xFFFFFFFF, _
FontSize As Float = 16) As B4XView
Dim Button As Button
Button.Initialize("Button")
Button.Text = Text
Dim View As B4XView = Button
View.SetLayoutAnimated(0, 0, 0, Width, Height)
View.Color = BackgroundColor
View.TextColor = TextColor
View.TextSize = FontSize
Return View
End Sub
Dim ConnectButton As B4XView = CreateStyledButton("Connect")
Dim DeleteButton As B4XView = CreateStyledButton( _
"Delete", 120dip, 45dip, 0xFFD32F2F)
Public Sub ExecQuerySingleResult(Query As String, _
Args As List = Null, _
DefaultValue As Object = Null) As Object
Dim Count As Object = ExecQuerySingleResult( _
"SELECT COUNT(*) FROM Users")
Dim UserName As Object = ExecQuerySingleResult( _
"SELECT Name FROM Users WHERE UserId = ?", _
Array(UserId))
Dim UserName As Object = ExecQuerySingleResult( _
"SELECT Name FROM Users WHERE UserId = ?", _
Array(UserId), _
"Unknown User")
ExecQuerySingleResult(Query)
ExecQuerySingleResult2(Query, Args)
ExecQuerySingleResultWithDefault(Query, Args, DefaultValue)
SaveMeasurement(UserId, Measurement)
Private Sub SaveMeasurement(UserId As String, _
Measurement As Map, _
SyncToCloud As Boolean)
SaveMeasurement(UserId, Measurement, True)
Private Sub SaveMeasurement(UserId As String, _
Measurement As Map, _
SyncToCloud As Boolean = True)
'Save the measurement...
End Sub
SaveMeasurement(UserId, Measurement)
SaveMeasurement(UserId, Measurement, False)
Null:Private Sub ShowUser(UserData As Map = Null)
If UserData = Null Then
Log("No user was provided")
Return
End If
Log(UserData.Get("Name"))
End Sub
ShowUser
ShowUser(CreateMap("Name": "Walter"))
Null is useful for optional objects such as:Null are not necessarily the same operation.Private Sub Test(Value As Object = 10)
Log(Value)
End Sub
Test
Test(Null)
Null.Null means.Private Sub LogEvent(Message As String, _
Level As String = "INFO")
Log(Level & ": " & Message)
End Sub
LogEvent("Application started")
LogEvent("Application started", "INFO")
LogEvent("Application started")
LogEvent("Application started", "INFO")
CallSub still require the expected arguments.Public Sub UpdateStatus(Status As String, _
Animate As Boolean = True)
'Update UI...
End Sub
UpdateStatus("Connected")
CallSub, CallSub2, and CallSub3 have their own fixed argument-count behavior.@DefaultValue annotation:public static String BytesToString(
byte[] data,
@DefaultValue("0") int startOffset,
@DefaultValue("-1") int length,
@DefaultValue("UTF-8") String charset) {
//Convert bytes to a string...
}
Dim Text As String = BytesToString(Data)
Dim Text As String = BytesToString( _
Data, 0, Data.Length, "CP-1252")
Connect(DeviceId, Timeout = 10000)
ShowNotification(Message, Sound = True, Duration = 3000)
SaveFile(Path, Data, Overwrite = False)
CalculateMeasurement(Landmarks, Scale = 1.0, _
ApplyCorrection = True)
SendEmail(Address, Subject, Body, IsHtml = False)
Private Sub TransferMoney(Account As String, _
Amount As Double = 1000)
End Sub
Private Sub TransferMoney(Account As String, _
Amount As Double)
End Sub
CreateReport(Name, "PDF", True, False, True, _
False, True, False)
True, False, True, False
Type ReportOptions( _
Format As String, _
IncludeImages As Boolean, _
Compress As Boolean, _
SendEmail As Boolean, _
SaveToCloud As Boolean)
Dim Options As ReportOptions
Options.Initialize
Options.Format = "PDF"
Options.IncludeImages = True
Options.SendEmail = True
CreateReport("Monthly Report", Options)
Connect(DeviceId, 10000, True, 3)
Connect(DeviceId)
SaveData(Data)
Private Sub SaveData(Data As Object, _
Compress As Boolean = False)
End Sub
CallSub calls still require the appropriate arguments.True, False, or 5000 in the wrong position.Thanks I think I understand this better.Imagine I have a sub for inserting or updating a row in database table.
In the pass, I need to use Array, Map, custom type to create a cleaner sub with single parameter or leave empty Strings when call it. It looks ugly and may need more lines of code.B4X:Sub Save (user_id As Int, user_name As String, user_age As Int, user_email As String, user_password As String, user_occupation As String) End Sub
NowB4X:Save(1, "John Cena", 21, "", "", "")
B4X:Save(1, "John Cena")
I think it is also useful for initializing values when create custom type.
B4X:Type User (user_id As Int, user_name As String, user_age As Int, user_email As String, user_password As String, user_occupation As String) Sub CreateUser(user_id As Int, user_name As String = "NoName", user_age As Int = 21, user_email As String, user_password As String = "default", user_occupation As String = "Actor") End Sub CreateUser (1, "John Cena")
No. It will be too confusing. How can the compiler / developer know which parameters are being set?will it be possible to pass like 2 parameters but that are not following?
anyfunction(num1=9, num3=20)
named arguments is the correct way or the only way i can think of making this possible is in events that have multiple types like: string, int, long,..No. It will be too confusing. How can the compiler / developer know which parameters are being set?
The Python solution for such cases is to use named arguments:
B4X:anyfunction(num1=9, num3=20)
I don't think that it will be added to B4X.
sub anyfunction(num1 as int = 5, num2 as int =10, txt as string = "sum")
log(txt & (num1+num2))
end sub
anyfucntion(2,"total ") 'LOG(total 12)'
sub anyfunction(num1 as int = 5, num2 as int =10, txt as string = "sum")
log(txt & (num1+num2))
end sub
anyfucntion(2,[def],"total ") 'LOG(total 12)'
We use cookies and similar technologies for the following purposes:
Do you accept cookies and these technologies?
We use cookies and similar technologies for the following purposes:
Do you accept cookies and these technologies?