bsky
bsky

Reputation: 20222

How to clone a Vector

I have the following method, where cards is of type Vector[Card]. As cards is a field, I want to return a clone of it.

I tried this:

class Deck(cards: Vector[Card] = Vector.empty[Card]) {

    //other methods

    def getCards(): Vector[Card] = {
        return cards.clone()
      }
}

However, I am getting:

Error:(31, 18) method clone in class Object cannot be accessed in Vector[<error>]
 Access to protected method clone not permitted because
 prefix type Vector[<error>] does not conform to
 class Deck in package genericGame where the access take place
    return cards.clone()
                 ^

So how can I clone the field?

Upvotes: 0

Views: 820

Answers (1)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

You don't have to, just return cards, cloning is usually needed for mutable objects where you need to take a copy of the object and work on them independently from source because the source can change later.

It is not the case for Vector since it is immutable, you can safely hold a reference to it and it will always hold the same value/s of Card unless Card itself is mutable, then you can add a method to copy a Card and do a map.

class Card(var name:String){
  def copy() = new Card(this.name)
}
val copy: Vector[Card] = vector.map(_.copy())

But as I said, all this wouldn't be needed if Card is immutable (case classes for instance) then you can safley use your Vector without any copies.

Upvotes: 3

Related Questions