B4J Question Copy type data to new var

canalrun

Well-Known Member
Licensed User
Longtime User
Hello,
I would like to create a second instance of a type variable and then copy the contents of of the first instance of that type variable to the second. I don't want to copy a reference to the first instance, I want to actually create a new variable instance that contains the same data.

Erel has and example in B4A using KeyValueStore. Is this available in B4J?

For example:
B4X:
Type MyPoint (l, t as Int)

Dim P1, P2 as MyPoint

P1.Initialize

P1.l = 5
P1.t = 10

P2.Initialize

P2 = CopyTheDataFrom(P1)

' if I do P2 = P1, P2 gets a reference to P1
' if I set P2.l = 7, P1.l would also be 7

Is there a way to do this other than writing a special function CopyTheDataFrom?

Thanks,
Barry.
 

stevel05

Expert
Licensed User
Longtime User
No, you have to clone each element at it's lowest level.
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
Very true, I have used it to clone and backup classes. For the example given it would be simpler to write a small subroutine.
 
Upvote 0

canalrun

Well-Known Member
Licensed User
Longtime User
Thanks both.

In a general sense, using KeyValueStore would probably be better, but for my simple case I went with the subroutine approach.

Something like:

B4X:
Sub CopyTheDataFrom(p1 as MyPoint) as MyPoint
  dim p2 as MyPoint

  p2.Initialize

  p2.l = p1.l
  p2.t = p1.t

  return(p2)
end sub

Then the code P2 = CopyTheDataFrom(P1) produces a new instance of MyPoint copying the data.

Barry.
 
Upvote 0
Top