Suppose I want to keep a reference to one of activity's views in a variable. So, I create a reference variable of the same type as the view. However, if I later change the value of that variable, it changes the original view, as well:
This code will produce the "java.lang.RuntimeException: Object should first be initialized (Label)." at the last line. Obviously, changing value of ref also changed the Label1 to point to the same thing (null in this case). Therefore, assignment to a View object produced the direct reference of the assigned View object. However, in the Tutorial "Variables & Objects in Basic4android" (https://www.b4x.com/android/forum/threads/variables-objects-in-basic4android.8385/), Erel said:
This is true if ref object is of type Object and we create a helper object of the appropriate type when we need to access the view's properties:
Now, ref holds the COPY of the reference, as it should, and assigning null to it doesn't change the Label1 variable and the error is not produced in the last line.
Finally, the question:
Why are view objects directly referenced on assignment, and other object are passed a reference copy?
B4X:
Dim Label1 as Label
Label1.Initialize("")
Label1.Text = "initial value"
Activity.AddView(Label1, 0, 0, 300, 100)
Dim ref as Label
ref = Label1
ref.Text = "ref variable assignment"
ref = null
Label1.Text = "Label1 variable assignment "
This code will produce the "java.lang.RuntimeException: Object should first be initialized (Label)." at the last line. Obviously, changing value of ref also changed the Label1 to point to the same thing (null in this case). Therefore, assignment to a View object produced the direct reference of the assigned View object. However, in the Tutorial "Variables & Objects in Basic4android" (https://www.b4x.com/android/forum/threads/variables-objects-in-basic4android.8385/), Erel said:
All other types, including arrays of primitives types and strings are categorized as non-primitive types.
When you pass a non-primitive to a sub or when you assign it to a different variable, a copy of the reference is passed.
This means that the data itself isn't duplicated.
It is slightly different than passing by reference as you cannot change the reference of the original variable.
This is true if ref object is of type Object and we create a helper object of the appropriate type when we need to access the view's properties:
B4X:
Dim Label1 as Label
Label1.Initialize("")
Label1.Text = "initial value"
Activity.AddView(Label1, 0, 0, 300, 100)
Dim ref as Object
ref = Label1
Dim helper as Label = ref
helper.Text = "ref variable assignment"
ref = null
Label1.Text = "Label1 variable assignment "
Now, ref holds the COPY of the reference, as it should, and assigning null to it doesn't change the Label1 variable and the error is not produced in the last line.
Finally, the question:
Why are view objects directly referenced on assignment, and other object are passed a reference copy?