B4J Question Single line initialization of a custom type

wl

Well-Known Member
Licensed User
Longtime User
Is there a fast way (single line) to initialize a variable of a customtype (set values to all members of the customtype of the variable to be initialized) . Something similar as CreateMap to easily initialize a map ?

Thanks

B4X:
Type
Declares a structure.
Can only be used inside sub Globals or sub Process_Globals.
Syntax:
Type type-name (field1, field2, ...)
Fields include name and type.
Example:
Type MyType (Name As String, Items(10) As Int)
Dim a, b As MyType
a.Initialize
a.Items(2) = 123
 

stevel05

Expert
Licensed User
Longtime User
The problem is that Types can include all kinds of objects which may need initializing. If they are anything other than simple, I usually create a sub specifically to do it:

B4X:
Type MyType(Name As String,Items() As Int, DataList As List)

Dim a As MyType = NewMyType("Name1")
Dim b As MyType = NewMyType("Name2")

Private Sub NewMyType(Name As String) As MyType
    Dim MT As MyType
    MT.Initialize
    MT.Name = Name
    Dim arr(10) As Int
    MT.Items = arr
    MT.DataList.Initialize
    Return MT
End Sub

You can be as creative as you like, for instance if you always want to initialize one (or more) values of the array, you can pass them as parameters and set them in the sub.
 
Last edited:
Upvote 0
Top