B4J Question Copy type data to new var

Discussion in 'B4J Questions' started by canalrun, Jan 26, 2015.

  1. canalrun

    canalrun Well-Known Member Licensed 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:
    Code:
    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.
     
  2. stevel05

    stevel05 Expert Licensed User

    No, you have to clone each element at it's lowest level.
     
  3. Erel

    Erel Administrator Staff Member Licensed User

    Yes. You can use KeyValueStore in B4J as well to clone an object: KeyValueStore
     
  4. stevel05

    stevel05 Expert Licensed 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.
     
  5. canalrun

    canalrun Well-Known Member Licensed 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:

    Code:
    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.
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice