hhp
hhp

Reputation: 129

Type mismatch even when Vector type has been declared

I have a very simple method in a class:

def partysCandidate(party: String): Vector[Candidate]= {
    var result = Vector[Candidate]()

    for (candidate <- this.candidates) {

      if (candidate.party == party) result = result + candidate
    }

    result
  }

However it gave me Error type mismatch found : package.Candidate required: String at result + candidate. I couldn't figure out why. Any help would be much appreciated.

Many thanks!

Upvotes: 1

Views: 63

Answers (1)

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27535

There is no method + on a Vector, there are +: (prepend), :+ (append) (colon is treated as mnemonic for collection), etc.

There is however any2stringadd implicit class which - when you call sth.+(x: String) on something which doesn't have such method - call .toString on sth before appending x to it, which would return String. This results in the error you see. Accidental usage of this extension method is a reason why this got deprecated and why many linters defend against it.

Your code could be fixed by using the right operator e.g.

if (candidate.party == party) result = result :+ candidate

however in this particular case you can just use for-comprenension to build the result without mutation

def partysCandidate(party: String): Vector[Candidate] =
   for {
     candidate <- candidates
     if candidate.party == party
   } yield candidate

or even shorter

def partysCandidate(party: String): Vector[Candidate] =
  candidates.filter(c => c.party == party)

Upvotes: 4

Related Questions